使用JavaScript来连接到WCF Web服务 [英] Use Javascript to connect to WCF Web Service
问题描述
有谁知道如何使用JavaScript来连接到一个WCF Web服务?
Does anyone know how to use Javascript to connect to a WCF Web Service?
我需要在这一点上是真正连接到Web服务,并通知连接成功。
All I need at this point is to actually connect to the web service, and be notified that the connection was successful.
有谁知道我能做到这一点?
Does anyone know how I can do this?
推荐答案
如果您的WCF服务是同一个域,你可以使用下面的函数,将执行调用
If your WCF service is within the same domain you might use the below function that would perform the call
function TestingWCFRestWithJson() {
$.ajax({
url: "http://localhost/Service/JSONService.svc/GetDate",
dataType: "json",
type: "GET",
success: function (data, textStatus, jqXHR) {
// perform a success processing
},
error: function (jqXHR, textStatus, errorThrown) {
// show error to the user about the failure to invoke the service
},
complete: function (jqXHR, textStatus) {//any process that needs to be done once the service call is compelte
}
});
}
如果您的WCF服务是比你调用应用程序域之外的其他一些领域,那么你就需要执行JSONP调用,如下所示:
If your WCF service is in some other domain other than your calling applications domain then you would need to perform a JSONP call as shown below:
function TestingWCFRestWithJsonp() {
$.ajax({
url: "http://domain.com/Service/JSONPService.svc/GetDate",
dataType: "jsonp",
type: "GET",
timeout: 10000,
jsonpCallback: "MyCallback",
success: function (data, textStatus, jqXHR) {
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
}
function MyCallback(data) {
alert(data);
}
在使用jQuery的$阿贾克斯完整/成功/错误的方法不会被触发,而如被触发,需要通过WCF服务进行处理的回调方法进行JSONP调用。存在由WCF框架标识,如果请求是一个JSONP呼叫并写入内容回流以调用与数据回调函数提供一个属性crossDomainScriptAccessEnabled。这是可用的结合元件上,如下所示:
When a JSONP call is performed using JQuery's $.ajax the complete/success/error methods are not fired rather a callback method as shown is fired which needs to be handled by the WCF service. There is a attribute "crossDomainScriptAccessEnabled" provided by the WCF framework that identifies if the request is a JSONP call and writes the content back to the stream to invoke the callback function with data. This is available on the binding element as shown below:
<webHttpBinding>
<binding name="defaultRestJsonp" crossDomainScriptAccessEnabled="true">
<readerQuotas maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647" maxDepth="64" maxNameTableCharCount="2147483647" />
<security mode="None" />
</binding>
</webHttpBinding>
这篇关于使用JavaScript来连接到WCF Web服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!