如何在不使用表单且没有回发的情况下在Javascript中发出简单的POST请求?
答案 0 :(得分:17)
虽然我从@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);
答案 1 :(得分:5)
我创建的功能是发送请求而不刷新页面,而不打开页面,没有AJAX 。进程对用户是不可见的。我使用假iframe发送请求:
/**
* 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);
}
现在你可以做到:
requestWithoutAjax('url/to', { id: 2, price: 2.5, lastname: 'Gamez'});
看看它是如何运作的!:http://jsfiddle.net/b87pzbye/10/。
答案 2 :(得分:3)
您可以使用AJAX调用(XMLHttpRequest对象)
来完成此操作