在html页面中,能实现跨域请求的是
第一:
<script src="http://localhost:59602/JsonpTest.ashx?callBack=callBack"></script>
第二:
var img = document.createElement("img");
img.src = "http://localhost:59602/JsonpTest1.ashx?callBack=callBack";
现在根据这两种讲解跨域请求
第一种:
直接上代码:前台HTML页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script> function callBack() { alert("执行了"); } </script> <script src="http://localhost:59602/JsonpTest.ashx?callBack=callBack"></script> </head> <body> </body> </html>
后台用的c#的一般处理程序
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string callBack= context.Request.QueryString["callBack"];
context.Response.Write(callBack+"()");
}
执行结果成功
第二种:
前台代码:html页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <!--<img src="http://localhost:59602/JsonpTest.ashx?callBack=callBack">--> </body> <script> var img = document.createElement("img"); img.src = "http://localhost:59602/JsonpTest1.ashx?callBack=callBack"; // img.style.display = "none"; document.body.appendChild(img); img.onload = function (data1) { console.log("成功"); } img.onerror = function (data1) { console.log("失败"); console.log(data1); } </script> </html>
后台代码:后台用的302重定向调整,直接返回图片也可以
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Redirect("https://img.alicdn.com/tfs/TB1cokKnY_I8KJjy1XaXXbsxpXa-190-140.gif", false);
}
第三中:JQ的ajax封装的jsonp,本质就是用的上面两种
前台页面:HTML
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script src="jquery-1.10.2.js"></script> <script> $(function () { $.ajax({ url:"http://localhost:59602/JsonpTest.ashx", dataType:"jsonp", jsonpCallback:"callback", success:function (data) { alert("回调成功"); } }); }); function callback(data) { alert("回调callback"); } </script> </head> <body> </body> </html>
后台代码用的第一中的。
结果:查看网络请求,本质还是第一种
后台接口永续跨域详解:https://blog.csdn.net/hehexiaoxia/article/details/61916737