通过jQuery调用JSON wcf服务
我有jQuery wcf方法从aspx页面与jQuery的问题。通过jQuery调用JSON wcf服务
这是我的测试方法:
[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");
}
}
此服务部署到IIS。 当我从Chrome调用此方法时:http://localhost/TestService/ServiceImpl.svc/Test 一切都很好,我可以看到结果。但是,当我从jQuery 调用它时,我有错误:NETWORK_ERR:XMLHttpRequest异常101.我尝试在Google中找到解决方案。 但结果并不成功。我如何解决它?
jQuery的电话:
<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" />
所以这是一个同源问题。 (请参阅here)
对于XMLHttpRequest,资源必须位于与请求它的页面完全相同的域。这是为了防止XSS(见here)。如果你想使用来自不同域的资源,你必须使用类似jsonp的东西。 (请参阅here)有关如何使用WCF执行此操作的好教程。
您提供的链接不再有效。 – PsychoDUCK
@PsychoDUCK我修复了这个链接。我收到的博客文章已不再可用。但我发现了另一个基本上提供相同信息的人 – albertjan
这可能是一个跨站点问题。你是否在同一个iis上托管你的html?看看这里:http://jasonkelly.net/2009/05/using-jquery-jsonp-for-cross-domain-ajax-with-wcf-services/。 – albertjan
我在IIS上托管服务,但是我的测试网站在Visual Studio Development Server上运行。 – ukraine
你好,你应该在同一个网站上托管它们。如果你想使用XMLHttpRequest,因为它不允许打开它的范围。这是为了防止XSS攻击。如果你想从一个不同的网站使用追索权,你将不得不使用类似jsonp的东西(请参阅我以前发布的内容)。 – albertjan