Simple ajax form using javascript no jQuery

前端 未结 9 1050
终归单人心
终归单人心 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:28

    The following is a far more elegant solution of the other answer, more fit for modern browsers.

    My reasoning is that if you need support for older browser you already most likely use a library like jQuery, and thus making this question pointless.

    /**
     * Takes a form node and sends it over AJAX.
     * @param {HTMLFormElement} form - Form node to send
     * @param {function} callback - Function to handle onload. 
     *                              this variable will be bound correctly.
     */
    
    function ajaxPost (form, callback) {
        var url = form.action,
            xhr = new XMLHttpRequest();
    
        //This is a bit tricky, [].fn.call(form.elements, ...) allows us to call .fn
        //on the form's elements, even though it's not an array. Effectively
        //Filtering all of the fields on the form
        var params = [].filter.call(form.elements, function(el) {
            //Allow only elements that don't have the 'checked' property
            //Or those who have it, and it's checked for them.
            return typeof(el.checked) === 'undefined' || el.checked;
            //Practically, filter out checkboxes/radios which aren't checekd.
        })
        .filter(function(el) { return !!el.name; }) //Nameless elements die.
        .filter(function(el) { return el.disabled; }) //Disabled elements die.
        .map(function(el) {
            //Map each field into a name=value string, make sure to properly escape!
            return encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value);
        }).join('&'); //Then join all the strings by &
    
        xhr.open("POST", url);
        // Changed from application/x-form-urlencoded to application/x-form-urlencoded
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
        //.bind ensures that this inside of the function is the XHR object.
        xhr.onload = callback.bind(xhr); 
    
        //All preperations are clear, send the request!
        xhr.send(params);
    }
    

    The above is supported in all major browsers, and IE9 and above.

提交回复
热议问题