Send POST data using XMLHttpRequest

前端 未结 13 1471
说谎
说谎 2020-11-21 04:27

I\'d like to send some data using an XMLHttpRequest in JavaScript.

Say I have the following form in HTML:

<         


        
13条回答
  •  日久生厌
    2020-11-21 04:48

    There's some duplicates that touch on this, and nobody really expounds on it. I'll borrow the accepted answer example to illustrate

    http.open('POST', url, true);
    http.send('lorem=ipsum&name=binny');
    

    I oversimplified this (I use http.onload(function() {}) instead of that answer's older methodology) for the sake of illustration. If you use this as-is, you'll find your server is probably interpreting the POST body as a string and not actual key=value parameters (i.e. PHP won't show any $_POST variables). You must pass the form header in to get that, and do that before http.send()

    http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    

    If you're using JSON and not URL-encoded data, pass application/json instead

提交回复
热议问题