【发布时间】:2010-06-15 22:24:10
【问题描述】:
我有一个简单的 ASP.NET Web 服务
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service () {
}
[WebMethod]
public string SetName(string name) {
return "hello my dear friend " + name;
}
}
我为此 Web 服务创建了虚拟目录,因此我可以通过点击接收访问权限 http://localhost:89/Service.asmx.
我尝试通过带有 jQuery 的简单 html 页面调用它。为此,我使用函数
CallWS() {
$.ajax({
type: "POST",
data: "{'name':'Pumba'}",
dataType: "json",
url: "http://localhost:89/Service.asmx/SetName",
contentType: "application/json; charset=utf-8",
success: function (msg) {
$('#DIVid').html(msg.d);
},
error: function (e) {
$('#DIVid').html("Error");
}
});
最有趣的事实:如果我使用我的 WebService 在项目中创建 html 页面并将 url 更改为 Service.asmx/SetName 一切都很好。 但是,如果我尝试远程调用此 Web 服务 - 成功功能有效,但 msg 为空。
之后我尝试通过 SOAP 调用此服务。它是一样的 - 在本地它工作得很好,但在远程 - 一点也不。
var ServiceUrl = 'http://localhost:89/Service.asmx?op=SetName';
function beginSetName(Name) {
var soapMessage = '<?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <SetName xmlns="http://tempuri.org/"> <name>' + Name + '</name> </SetName> </soap:Body> </soap:Envelope>';
$.ajax({
url: ServiceUrl,
type: "POST",
dataType: "xml",
data: soapMessage,
complete: endSetName,
contentType: "text/xml; charset=\"utf-8\""
});
return false;
}
function endSetName(xmlHttpRequest, status)
{
$(xmlHttpRequest.responseXML)
.find('SetNameResult')
.each(function () {
var name = $(this).text();
alert(name);
});
}
在这种情况下,状态的值为“parseerror”。 你能帮我解决这个问题吗?我应该怎么做才能通过 jQuery 通过 url 远程调用另一个 WebService。
提前谢谢你, 格雷格
【问题讨论】:
-
这一定是这里最常见的问题之一。您不能使用 XMLHttpRequest 向与您的页面来自的域不同的域发出请求。
-
那么在这种情况下有什么解决办法呢?
-
问题是我需要创建 SideBar Gadget 并且需要使用 web 服务...这就是为什么使用这样的架构非常有必要。
标签: jquery ajax web-services