使用jsonp跨域请求

一、异步对象,不能实现跨域请求

在站点A中访问站点B的数据:

站点A代码:

 1     window.onload = function () {
 2             document.getElementById("btnAjax").onclick = doAjax;
 3         }
 4         function doAjax() {
 5             var xhr = new XMLHttpRequest();
 6             xhr.open("get", "http://www.ruanmou.net/C01Target.ashx", true);
 7             xhr.setRequestHeader("If-Modified-Since", "0");
 8             xhr.onreadystatechange = function () {
 9 
10                 if (xhr.readyState == 4 && xhr.status == 200) {
11                     var res = xhr.responseText;
12                     alert(res);
13                 }
14             };
15             xhr.send(null);
16         }
<input type="button" value="使用异步请求跨域请求是错的" id="btnAjax" />

站点B代码:

C01Target.ashx中:

1 public void ProcessRequest(HttpContext context)
2         {
3             context.Response.ContentType = "text/plain";
4             context.Response.Write(“hello world”);
5         }

二、使用script标签实现跨域请求

站点A代码:

 <script type="text/javascript" src="http://www.ruanmou.net/C01Target.ashx?callback=showData"></script>
1  function showData(data) {
2             for (var key in data) {
3                 alert(data[key]);
4             }
5         }

站点B代码:

C01Target.ashx中:

1 public void ProcessRequest(HttpContext context)
2         {
3             string funName = context.Request.Params["callback"];
4             context.Response.ContentType = "text/plain";
5             string strDate = funName+"({\"name\":\"Xuj\",\"age\":\"18\"})";//返回数据为json格式
6             context.Response.Write(strDate);
7         }

 三、jquery使用jsonp实现跨域请求

站点A代码:

 1 window.onload = function () {
 2             document.getElementById("btnAjax").onclick = doAjax;
 3         }
 4         function doJq() {
 5             $.ajax("http://www.ruanmou.net/C01Target.ashx"), {
 6                 type: "get",//内部就是创建一个script标签
 7                 jsonp:"callback",//传的参数名,和服务器端一致
 8                 dataType: "jsonp",//指定回调的函数名
 9                 jsonCallback: "showData",
10                 success: function () {
11                     alert("11111");
12                 }
13             });
14         }
1 function showData(data) {
2             for (var key in data) {
3                 alert(data[key]);
4             }
5         }

 

posted @ 2014-04-19 14:12  蜡笔小新111  阅读(628)  评论(0编辑  收藏  举报