POST请求(JavaScript)

kyks70gy  于 5个月前  发布在  Java
关注(0)|答案(3)|浏览(68)

如何在不使用表单和不回发的情况下用JavaScript发出简单的POST请求?

cedebl8k

cedebl8k1#

虽然我从@sundeep answer中获取了代码样本,但为了完整起见,我将代码发布在这里

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);

字符串

7fhtutme

7fhtutme2#

您可以使用AJAX调用(XMLHttpRequest对象)来实现这一点
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php

fnatzsnv

fnatzsnv3#

我做了一个函数,发送请求时不刷新页面,不打开页面,不使用AJAX,过程对用户是不可见的,我使用一个false iframe发送请求:

/**
* Make a request without Ajax and without refreshing 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 an 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);
}

字符串
现在你可以做到:

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


查看如何工作!:http://jsfiddle.net/b87pzbye/10/.

相关问题