json替换jsonp实现跨域请求

最近遇到h5前端页面和web后端双方的请求存在跨域,普通的jquery.ajax请求已不能实现(因为js是不允许跨域的(如果可以跨域,那就能随便改别人的网页了),js的原理),

最后经过艰苦奋斗,终于初步实现了,虽然会有那么一点的不安全,但只要接口判断好就会减少很多不安全...

前端页面ajax请求如下:

$.ajax({
url: "http://www.xxx.com/ashx/xx.ashx",
type: "post",
cache: false,
data: {xx:xx},
dataType: "json",
crossDomain: true,
xhrFields: {
'Access-Control-Allow-Origin': '*'
},
success: function (data) {

}
});

前端重要的这两句,一定要加上,具体意思是允许跨域,允许所有的请求:

后端在webconfig文件里面添加这句,服务端也允许跨域即可

<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>

原文地址:https://www.cnblogs.com/zhy-1992/p/6772541.html