How do I pass along variables with XMLHTTPRequest

后端 未结 7 803
孤街浪徒
孤街浪徒 2020-11-30 03:47

How do I send variables to the server with XMLHTTPRequest? Would I just add them to the end of the URL of the GET request, like ?variable1=?v

7条回答
  •  抹茶落季
    2020-11-30 04:15

    If you want to pass variables to the server using GET that would be the way yes. Remember to escape (urlencode) them properly!

    It is also possible to use POST, if you dont want your variables to be visible.

    A complete sample would be:

    var url = "bla.php";
    var params = "somevariable=somevalue&anothervariable=anothervalue";
    var http = new XMLHttpRequest();
    
    http.open("GET", url+"?"+params, true);
    http.onreadystatechange = function()
    {
        if(http.readyState == 4 && http.status == 200) {
            alert(http.responseText);
        }
    }
    http.send(null);
    

    To test this, (using PHP) you could var_dump $_GET to see what you retrieve.

提交回复
热议问题