jQuery Ajax 调用WebService实例详解

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格式,使用将双引号转义。
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>

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值