AJAX - Using POST instead of GET

后端 未结 2 1922
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 12:49

Up until now I have been using:

xmlhttp.open(\"GET\",\"server_script.php?q=\"+str,true);

Thanks

Edit: I am providing a solution for an

相关标签:
2条回答
  • 2021-01-22 13:10

    this is how you would use post:

    var url = "server_script.php";
    var params = "q="+str;
    xmlhttp.open("POST", url, true);
    
    //Send the proper header information along with the request
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");
    
    xmlhttp.onreadystatechange = function() {//Call a function when the state changes.
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            alert(xmlhttp.responseText);
        }
    }
    xmlhttp.send(params);
    

    source

    0 讨论(0)
  • 2021-01-22 13:12

    The query you show is probably perfectly fine as a GET request. No need to change it.

    There are reasons to use one over the other: Requests that change state on server side (i.e. change data) should generally use POST; "read" requests should be GET.

    This comes with an implicit security advantage because you can't do any damage by smuggling an URL into a user's page (like, showing an image whose URL points to an admin page named deleteall.php).

    If your request just retrieves data, you're perfectly fine staying with GET.

    See this question for an extensive discussion on when to use which. GET vs POST in AJAX?

    0 讨论(0)
提交回复
热议问题