我已经创建了一个网络服务并想从 javascript 调用它,为此我在我的页面的脚本管理器中注册了 ServiceReference,并使用命名空间调用了网络服务。
我的问题是我想等到收到网络服务的响应。
为此,我尝试使用 setInterval,但这不起作用。
还有其他方法可以实现吗?
更多详情如下: 在 Javascript 中,如果您编写一个函数来调用 WebService,您必须向它传递一个方法签名,该方法签名将在 webservice 发送响应后调用。
例如
var IsResponseReceived;
function GetSomethingFromWebService()
{
IsResponseReceived = 'No';
Namespace.WebServiceClass.GetMeSomething(parameter1,SuccessResponseReceiver);
alert(webServiceResponse);
}
function SuccessResponseReceiver(parameter1,parameter2)
{
IsResponseReceived = 'Yes';
}
在上面的代码中,我的警报每次都显示“否”。我想在警报和网络服务调用之间写一些代码,让我等到收到响应。
我现在清楚了吗?
最佳答案
如果您考虑使用纯 JavaScript(现在很不寻常),请考虑此代码
var strURL = "localhost/services/foobar.svc";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('GET', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
// do whatever you want to do when your service responded
// you may get the response content using self.xmlHttpReq.responseText
}
}
self.xmlHttpReq.send();
如果您考虑使用 jQuery (这是周围流行的 JavaScript 框架之一),很简单:
$.ajax({
url: "localhost/services/foobar.svc",
success: function(data){
// this is fired on successful response
// you will have response content in data parameter
}
});
关于javascript - 从 javascript 调用 webservice 并等待响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8228763/