解决jquery调用NET webservice跨域的问题

声明,解决方案由网上收集而来,个人整理。有别人的,也有我的。

一、webserive端

1.web.config

需要在web.config的configuration节点中加入如下的黑体部分内容。

  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet" />
        <add name="HttpPost" />
      </protocols>
    </webServices>
  </system.web>

再加入以下内容

  <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.asm.x

还不清楚是否必须在类前要加上以下内容。没时间测

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    [System.Web.Script.Services.ScriptService]

 

3.一个方法

        [WebMethod]
        public string getProduct()
        {
            DataTable dt = BizLogic.ProductsBLL.GetProductInfo();
            HttpContext.Current.Response.ContentType = "application/json";
            HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

            var obj = new
            {
                Status = 1,
                Data = dt
            };
            return Newtonsoft.Json.JsonConvert.SerializeObject(obj);
        }

二。JS部分

var svr_url = "http://192.168.2.23:9001/******.asmx/";

function getdata(action,para,callback)
{
    var uu = svr_url + action;
    $.ajax({
        type: "post",
        contentType:"application/json",
        data:para,
        url:svr_url + action,
        dataType:'json',
        success:function(result){  
            console.log(result);
            var res=JSON.parse(result.d);
            if(res.Status==1){
                if(callback)callback(res.data);
            }
            else
            {
                alert(res.Message);
            }
        },
        error:function(err){
            console.log(err);
        }
    });  
}

 

三。HTML页面

  getdata('getProduct',[],afterGet); 

  var afterGet=function(data)

  {

    ......

  }

 

 

以上实测通过,系统运行中。

 

posted @ 2017-01-05 17:39  jfcai  阅读(2557)  评论(1编辑  收藏  举报