AJAX XMLHttpRequest POST

后端 未结 2 1245
长情又很酷
长情又很酷 2020-12-03 08:17

I\'m trying to write an XMLHttpRequest using the POST method. I have managed to use XMLHttpRequest in the past using the GET method but am struggling with POST.

Here

2条回答
  •  死守一世寂寞
    2020-12-03 08:48

    You forgot to explicitly set to Content-type header, which is necessary when doing POST requests.

    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    

    Also, do not forget to use encodeURIComponent to properly encode your parameters, e.g.:

    var params = "var=" + encodeURIComponent("1");
    

    (in this particular example, it's not necessary, but when using special characters like + things will go horribly wrong if you don't encode the parameter text).

    Update – you should also replace all instances of %20 with +, like

    var params = params.replace(/%20/g, '+');
    

提交回复
热议问题