Simple ajax form using javascript no jQuery

前端 未结 9 1048
终归单人心
终归单人心 2020-11-28 11:46

I\'m working with a form for which the mark-up I can\'t change & can\'t use jQuery. Currently the form post the results to a new window. Is it possible to change this to

9条回答
  •  醉梦人生
    2020-11-28 12:24

    Expanding on Madara's answer: I had to make some changes to make it work on Chrome 47.0.2526.80 (not tested on anything else). Hopefully this can save someone some time.

    This snippet is a modification of that answer with the following changes:

    • filter !el.disabled,
    • check type of input before excluding !checked
    • Request type to x-www-form-urlencoded

    With the following result:

    function ajaxSubmit(form, callback) {
        var xhr = new XMLHttpRequest();
        var params = [].filter.call(form.elements, function (el) {return !(el.type in ['checkbox', 'radio']) || el.checked;})
        .filter(function(el) { return !!el.name; }) //Nameless elements die.
        .filter(function(el) { return !el.disabled; }) //Disabled elements die.
        .map(function(el) {
            return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
        }).join('&'); //Then join all the strings by &
        xhr.open("POST", form.action);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.onload = callback.bind(xhr);
        xhr.send(params);
    };
    

提交回复
热议问题