如何在javascript中实现异步服务调用

How to implement asynchronous service call in javascript?

本文关键字:异步 服务 调用 实现 javascript      更新时间:2023-09-26

我想异步调用我的服务器。

我的代码如下:-

function GetSynchronousJSONResponse(url, postData) {
var xmlhttp = null;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject) {
if (new ActiveXObject("Microsoft.XMLHTTP"))
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
else
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open("POST", url, false);
xmlhttp.send(postData);
var responseText = xmlhttp.responseText;
return responseText;
}

但服务调用给出"错误请求"错误。请帮助

您忘记在请求中添加内容类型。请在下面添加行,然后重试xmlhttp.setRequestHeader("内容类型","application/json;charset=utf-8");

函数GetSynchronousJSONResponse(URL,postData){

        $.ajax({
           url : URL,
           type : "POST",
           data : JSON.stringify(postData),//if required
           contentType : 'application/json',
           success : function(data) {}
   })
}

你可以试试这个