Call JSON wcf service via jQuery
I have question according calling json wcf methods from aspx page with jQuery.
This is my test method:
[ServiceContract]
public interface IEParcelService
{
[OperationContract]
[WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "Test")]
Response<string> Test();
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class EParcelServiceImpl : IEParcelService
{
public Response<string> Test()
{
return WebServiceHelper.Execute(() => "Test Message");
}
}
This service deployed to IIS. When I call this method from Chrome: http://localhost/TestService/ServiceImpl.svc/Test Everything is ok and I can see the result. But when I call it from jQuery I have error: NETWORK_ERR: XMLHttpRequest Exception 101. I tr开发者_如何学Cy to find solution in Google. But the result was not successful. How I can solve it?
jQuery call:
<script language="javascript">
$().ready(function () {
$("#myButt").click(function () {
$.ajax({
cache: false,
async: false,
type: "GET",
url: "http://localhost/EParselService/EParcelServiceImpl.svc/Test",
contentType: "application/json",
dataType: "json",
success: function (data, textStatus){
alert('successCallBack called');
alert(data);
alert(textStatus);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('errorCallBack called');
alert('textStatus = ' + textStatus + '/nerrorThrown = ' + errorThrown);
}
});
alert('Done!');
});
});
</script>
<input type="button" value="Get values from server" id="myButt" />
So it's a same-origin issue. (see here)
For a XMLHttpRequest the resource has to be on the exact same domain as the page requesting it. This is to prevent XSS (see here) atacks. If you want to use a resource from a different domain you'll have to use something like jsonp. (see here) For a good tutorial how to do this with WCF.
精彩评论