Cross-domain calling a WCF Service
I have a WCF service, this is a method which I'd to call:
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Json)]
double?[] GetPoints(string tourname);
I checked by WCF Test Client, it works fine
So I need to call this method from html page. It should work from other computer that is cross-domain.
I wrote somethig using jQuery 1-6-2.min.js:
var varType;
var varUrl;
var varData;
var varContentType;
var varDataType;
var varProcessData;
function CallService() {
alert("CallService");
$.ajax({
type : varType, //GET or POST or PUT or DELETE verb
开发者_运维技巧 url : varUrl, // Location of the service
data : varData, //Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, //Expected data format from server
processdata : varProcessData, //True or False
success : function(msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function Start() {
varType = "POST";
varUrl = "http://localhost:1592/TourService.svc/GetPoints";
varData = '{"tourname ":"customname"}';
varContentType = "application/json; charset=utf-8";
varDataType = "json";
varProcessData = true;
CallService();
}
function ServiceSucceeded(result) {
alert("ServiceSucceeded");
alert(result);
}
function ServiceFailed(result) {
alert('Service call failed: ' + result.status + ' ' + result.statusText);
varType = null;
varUrl = null;
varData = null;
varContentType = null;
varDataType = null;
varProcessData = null;
}
However ServiceFailed function is invoked with message "Service call failed 0 error"
How to make a cross-domain calling of WCF service?(using jQuery or not)
Thanks
Basically you need to be using jSONP instead of jSON:
Using jQuery & JSONP for cross-domain AJAX with WCF services
I'll provide a summary shortly in case this link disappears.
Also see the jQuery documentation for more about how to use jSONP, jQuery & AJAX
.net framework 4 for wcf has json call back inbuilt now ,
I think jquery1.5 onwards they added the following option , crossDomain , try the below code
$.ajax({
type: "POST",
dataType: "html",
crossDomain: true,
url: "http://www.domain.com/page.aspx",
error: function() {
alert("error");
},
success: function(msg){
alert(msg );
}
});
精彩评论