ajax跨域请求调用webservice接口

1.WebService 接口编写web

步骤:新建web项目=》添加web service=》编写方法接口=》而后发布(本地测试能够直接把这个web service运行起来)。ajax

关键如何让外部Ajax 调用。json

首先,配置WebService 项目配置文件(web.config)红色部分必须配置,这样第三方才能调用接口方法(经测试经过,直接粘贴就ok),不懂能够百度。app

 

<configuration>
    <system.web>
      <webServices> <protocols> <add name="HttpSoap"/> <add name="HttpPost"/> <add name="HttpGet"/> <add name="Documentation"/> </protocols> </webServices>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
  <system.webServer> <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>
</configuration>

二、其次,这里贴出WebService 中代码部分,这里我自定义一个返回一个Person集合GetPersonList(),可供Ajax调用。post

(1)发布时须要配置[WebService(Namespace = "http://192.168.1.90:5555/")]//这里定义你发布之后的域名地址。固然本地测试使用localhost就能够或者使用默认的便可。测试

(2)要放开[System.Web.Script.Services.ScriptService] 的注释。url

以上两步作到写接口发布WebService,访问http://192.168.1.90:5555/XXX.asmx 地址。spa

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace MyWebService
{
    /// <summary>
    /// MyWebService 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://localhost:47737/")] 
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要容许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消注释如下行。 
    [System.Web.Script.Services.ScriptService]
    public class MyWebService : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public int Add(int num1,int num2)
        {
            return num1 + num2;
        }
    }
}

3.第三方Ajax调用。debug

$.ajax({
                url: "http://localhost:47737/MyWebService.asmx/Add",
                type: "post",
                data: "{ 'num1': 2,'num2': 5 }",
                contentType: "application/json",
                dataType: "json",
                success: function (data) {
                    alert(data.d);
                },
                error: function () {
                    alert("发送ajax请求失败!");
                }
            });

注意:这里data是响应的结果,使用data.d获取数据,是由于返回来的数据格式为:{"d":7}code

相关文章
相关标签/搜索