XMLHttpRequest to Post HTML Form

后端 未结 6 1998
遇见更好的自我
遇见更好的自我 2020-12-01 04:50

Current Setup

I have an HTML form like so.

6条回答
  •  有刺的猬
    2020-12-01 05:29

    The POST string format is the following:

    name=value&name2=value2&name3=value3
    


    So you have to grab all names, their values and put them into that format. You can either iterate all input elements or get specific ones by calling document.getElementById().

    Warning: You have to use encodeURIComponent() for all names and especially for the values so that possible & contained in the strings do not break the format.

    Example:

    var input = document.getElementById("my-input-id");
    var inputData = encodeURIComponent(input.value);
    
    request.send("action=dosomething&" + input.name + "=" + inputData);
    

    Another far simpler option would be to use FormData objects. Such an object can hold name and value pairs.

    Luckily, we can construct a FormData object from an existing form and we can send it it directly to XMLHttpRequest's method send():

    var formData = new FormData( document.getElementById("my-form-id") );
    xhr.send(formData);
    

提交回复
热议问题