有什么方法可以在JavaScript中使用GET和POST方法,就像在PHP中一样吗?当然,我可以使用 PHP 在脚本标签中回显 javascript 代码,但就我而言,这是不可能的......
XMLHttpRequest 就是你需要的。这是与服务器通信的本机方式。
此外,由于@charlietfl,更现代的方法是使用 fetch,但在 IE 中不受支持。
如前所述,您可以尝试获取,但以下代码示例也可能对您有用 - 同时。只需使用正确的参数调用ajaxPOST(postParams, url(。
//This function creates cross-browser XMLHttp object
function createXMLHttp(){
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
var aVersions = [ "MSXML2.XMLHttp.9.0",
"MSXML2.XMLHttp.8.0",
"MSXML2.XMLHttp.7.0",
"MSXML2.XMLHttp.6.0",
"MSXML2.XMLHttp.5.0",
"MSXML2.XMLHttp.4.0","MSXML2.XMLHttp.3.0",
"MSXML2.XMLHttp","Microsoft.XMLHttp"
];
for (var i = 0; i < aVersions.length; i++) {
try {
var oXmlHttp = new ActiveXObject(aVersions[i]);
return oXmlHttp;
} catch (oError) {
//Do nothing
}
}
}
//if it reaches here, this cannot be created
throw new Error("XMLHttp object could be created.");
}
//this does Ajax POST
//sample params: var postParams = "key1="+value1+"&key2="+value2+"&keyx="+valuex;
function ajaxPOST(postParams, url){
var retString = false;
//creating xbrowser xmlhttp object; you handle any failures here
var http = createXMLHttp();
//setting headers
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//call-back handler
http.onreadystatechange = function() {
if(http.readyState == 4) {
if(http.status == 200) {
//this went fine
}
//read results now, you may trim it for extra spaces
retString = http.responseText;
//alert("retString: "+ retString);
}
return retString;
}
//send the request
http.send(postParams);
}