POST Request (Javascript)

前端 未结 3 869
野趣味
野趣味 2020-12-06 00:33

How do you make a simple POST request in Javascript without using a forms and without posting back?

相关标签:
3条回答
  • 2020-12-06 00:54

    Though I am taking the code sample from @sundeep answer, but posting the code here for completeness

    var url = "sample-url.php";
    var params = "lorem=ipsum&name=alpha";
    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    
    //Send the proper header information along with the request
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    
    xhr.send(params);
    
    0 讨论(0)
  • 2020-12-06 01:00

    You can do this using AJAX calls (XMLHttpRequest object)

    http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

    0 讨论(0)
  • 2020-12-06 01:05

    I have made a function that send a request without refresh the page, without open a page and without AJAX. The proccess is invisible to the user. I use a false iframe to send a request:

    /**
    * Make a request without ajax and without refresh the page
    * Invisible for the user
    * @param url string
    * @param params object
    * @param method string get or post
    **/
    function requestWithoutAjax( url, params, method ){
    
        params = params || {};
        method = method || "post";
    
        // function to remove the iframe
        var removeIframe = function( iframe ){
            iframe.parentElement.removeChild(iframe);
        };
    
        // make a iframe...
        var iframe = document.createElement('iframe');
        iframe.style.display = 'none';
    
        iframe.onload = function(){
            var iframeDoc = this.contentWindow.document;
    
            // Make a invisible form
            var form = iframeDoc.createElement('form');
            form.method = method;
            form.action = url;
            iframeDoc.body.appendChild(form);
    
            // pass the parameters
            for( var name in params ){
                var input = iframeDoc.createElement('input');
                input.type = 'hidden';
                input.name = name;
                input.value = params[name];
                form.appendChild(input);
            }
    
            form.submit();
            // remove the iframe
            setTimeout( function(){ 
                removeIframe(iframe);
            }, 500);
        };
    
        document.body.appendChild(iframe);
    }
    

    Now you can do it:

    requestWithoutAjax('url/to', { id: 2, price: 2.5, lastname: 'Gamez'});
    

    See how works!: http://jsfiddle.net/b87pzbye/10/.

    0 讨论(0)
提交回复
热议问题