总结下之前项目中用到的ajax跨域调用方法的解决方案。

简单说下jquery的jsonp的实现原理,首先在客户端通过jsonp去调用一个远程地址时,实际上jquery是在我们的表单中生成了一个script的标签,他的src是我们需要调用的远程地址的绝对路径,比如:www.mixls.com/dota/appController/SyncHistory.当请求到之后,controller端获取相应,实现数据的获取,并以一个类似:”callback(historyData);“的形式return,然后在客户端之前生成的srcipt标签中,就会写出这段代码,就像去请求一个普通的html文档一样,输出到了客户端,当我们的jsonp方法中,注册了这个callback方法,我们的success事件,就接受到了服务器返回的数据了。

客户端:

$.ajax({
        dataType: 'jsonp',
        jsonp: 'callback',
        //type:"post",
        url: “Test/SendMail",
        success: function (r) {
            alert(r.id);
        }
    });

服务器端:

 1 public ActionResult SendMail(string callback)
 2         {
 3            //   获取数据 
 4  
 5             return ContentJsonP(callback, result);
 6 
 7         }
 8 
 9 protected internal ContentResult ContentJsonP(string cl, object jsonObj)
10         {
11             ContentResult result = new ContentResult();
12             result.Content = cl + "(" + Helper.SerializationHelper.ObjToJsonString(jsonObj) + ")";
13             return result;
14         }
View Code

 

posted on 2013-07-12 10:43  mixls1234  阅读(235)  评论(0编辑  收藏  举报