JQuery Ajax调用webservice的一些经验记录,在此实例中,解决跨域使用了Core解决方案,在下一篇文章中,会介绍JS 跨域的问题。
- 实例!、实例!、实例!
- 跨域解决方案
实例-源码
前端
function SendPost(){
$.ajax({
'url':'http://100.80.62.40:8080/WebService.asmx/HelloWorld',
'type':'POST',
'contentType': "application/json; charset=utf-8",
'data':'',
'dataType':'json',
'success': function(response){
console.log(response);
console.log(response.d);
console.log(JSON.parse(response.d));
}
});
}
这里还是有个小问题的,顺便介绍一下吧。那就关于JSON.parse解析的问题,其实这个是小问题,JSON 的这个正确格式为 :{“result”:”success”},注意内容一定为双引号,不能为单引号,单引号就会出现如此的错误。故在webservic方法中为正确使用 json格式,使用将双引号转义。
,
WebService
[WebMethod]
public string HelloWorld()
{
return "{\"result\":\"success\"}";
}
Web.Config
system.web, 注意关于WebService及其子标签的写法
<system.web>
<compilation targetFramework="4.5.2" debug="true"/>
<httpRuntime targetFramework="4.5.2"/>
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
</httpModules>
<!--跨域请求-->
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
第二部分,这一块是为了解决JS 本源策略,跨域的问题。允许非同源调用
<system.webServer>
<!--解决跨域请求 by wys -->
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Methods" value="OPTIONS,POST,GET"/>
<add name="Access-Control-Allow-Headers" value="x-requested-with,content-type"/>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>