POST 请求(Javascript)

问题描述 投票:0回答:3

如何在 Javascript 中发出简单的 POST 请求而不使用表单且不回发?

javascript html post
3个回答
34
投票

虽然我从 @sundeep 答案中获取代码示例,但为了完整性起见,将代码发布在此处

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

4
投票

您可以使用 AJAX 调用(XMLHttpRequest 对象)来完成此操作

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


3
投票

我制作了一个发送请求的功能,无需刷新页面,无需打开页面,并且无需AJAX。该过程对用户来说是不可见的。我使用错误的 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/.

© www.soinside.com 2019 - 2024. All rights reserved.