Ajax跨域解决方案
GET方法 var url = "http://192.168.1.175:20000/api/user/ GetUser?id=1"; $.ajax({ url: url, dataType: 'json', contentType: "application/json; charset=utf-8", processData: false, type: 'get', success: function (data) { console.log(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(textStatus); } }); GET: var url = "http://192.168.1.175:20000/api/user/GetUser?id=1"; $.getJSON(url, "", function (jsonData) { console.log(jsonData); }); POST: var objData = { 'ID': 1, 'Name': '石榴', 'Pwd': '123456' } var url = "http://192.168.1.175:20000/api/user/PostAddUser"; $.post(url, objData, function (jsonData) { console.log(jsonData); });
$.ajax({ url:"http://192.168.1.175:10001/test.ashx", dataType: 'jsonp', jsonp: "jsonpcallback",//用于后台接收 返回 processData: false, type:'get', success: function (data) { console.log(data); }, error:function(XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(textStatus); }});
一般处理程序
context.Response.ContentType = "application/json"; string JsonData = "{\"TID\":\"1\",\"tList\":[{\"errcode\":\"快捷方式打开\",\"errmsg\":null,\"msgid\":null,\"expires_in\":\"20170301\",\"ticket\":\"4242\"},{\"errcode\":null,\"errmsg\":null,\"msgid\":null,\"expires_in\":\"20170301\",\"ticket\":\"4242\"}]}"; //必须和ajax [jsonp]对应 String jsoncallback = context.Request["jsonpcallback"]; context.Response.Write(jsoncallback + "(" + JsonData + ")");
IIS web.config 写上配置基本上能解决跨域问题(既API所在服务器)
<system.webServer> <httpProtocol> <customHeaders> <add name="Access-Control-Allow-Origin" value="*"/> <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS"/> <add name="Access-Control-Allow-Headers" value="Content-Type"/> </customHeaders> </httpProtocol> </system.webServer>
如果web.config不增加 需要增加以下代码 指定那个域可以访问 此接口
//所有 var result = new HttpResponseMessage { Content = new StringContent(josn, Encoding.GetEncoding("UTF-8"), "application/json") }; //HttpResponseHeaders hrh = result.Headers; //hrh.Add("Access-Control-Allow-Origin", "*");
//指定域 response.setHeader("Access-Control-Allow-Origin", "http://localhost:9105");