Jquery ajax jsonp cross-domain call example code

What is cross domain?

To put it simply, for security reasons, JavaScript in the page cannot access data on other servers, that is, the "same origin policy". And cross-domain is to bypass the restrictions of the same-origin policy through some means to achieve the effect of communication between different servers.

The specific policy restrictions can be seen in the table below:

URL illustrate allow communication
http://www.a.com/a.js
http://www.a.com/b.js
under the same domain name allow
http://www.a.com/lab/a.js
http://www.a.com/script/b.js
Different folders under the same domain name allow
http://www.a.com:8000/a.js
http://www.a.com/b.js
Same domain name, different ports not allowed
http://www.a.com/a.js
https://www.a.com/b.js
Same domain name, different protocols not allowed
http://www.a.com/a.js
http://127.0.0.100/b.js
Domain name and domain name corresponding ip not allowed
http://www.a.com/a.js
http://script.a.com/b.js
Same main domain, different subdomains not allowed
http://www.a.com/a.js
http://a.com/b.js
Same domain name, different second-level domain names (same as above) not allowed
http://www.a.com/a.js
http://www.b.com/b.js
different domain names not allowed

What is JSONP?

JSON (JavaScript Object Notation) is a lightweight data exchange format, and JSONP (JSON with Padding) is a "usage mode" of JSON, through which data can be obtained across domains. 

The principle of JSONP cross-domain

Under the same-origin policy, pages under a certain server cannot obtain data other than the server, but img, iframe, script and other tags are exceptions, and these tags can request data on other servers through the src attribute. Using the open strategy of the script tag, we can implement cross-domain request data. Of course, the cooperation of the server is also required. When we normally request a JSON data, the server returns a string of JSON data, and when we use the JSONP mode to request data, the server returns an executable JavaScript code.

For example, if the data to be obtained from the server (http://www.a.com/user?id=123) is as follows:

 
 
  1. {"id": 123, "name" : 张三, "age": 17}

Then, the data requested using JSONP (http://www.a.com/user?id=123?callback=foo) will be as follows: 

 
 
  1. foo({"id": 123, "name" : 张三, "age": 17});

Of course, if the server considers it more fully, the returned data may be as follows: 

 
 
  1. try{foo({"id": 123, "name" : 张三, "age": 17});}catch(e){}

At this time, we only need to define a foo() function, and dynamically create a script tag whose src attribute is http://www.a.com/user?id=123?callback=foo: 

function executeJsonp(url){
  var eleScript= document.createElement("script");
  eleScript.type = "text/javascript";
  eleScript.src = url;
  document.getElementsByTagName("head")[0].appendChild(eleScript);
}

function foo(data){
    for(var p in data){
      console.log(data[p]);
    }
}

var url = "http://www.a.com/user?id=123?callback=foo";
executeJsonp(url)

Then you can use the foo function to call the returned data. 

How to get data across domains through JSONP in jQuery

The first way is to set the dataType to 'jsonp' in the ajax function: 

 
 
  1. $.ajax({
  2.         dataType: 'jsonp',
  3.         url: 'http://www.a.com/user?id=123',
  4.         success: function(data){
  5.                 //Process data data
  6.         }
  7. });

The second method is to use getJSON to achieve, just add the callback=? parameter to the address: 

 
 
  1. $.getJSON('http://www.a.com/user?id=123&callback=?', function(data){
  2.         //Process data data
  3. });

It is also possible to simply use the getScript method:

 
 
  1. // At this time, the foo method can also be defined outside the function
  2. function foo(data){
  3.         //Process data data
  4. }
  5. $.getJSON('http://www.a.com/user?id=123&callback=foo');

Application of JSONP

JSONP can play a very important role in the open API. The open API is used in the developer's own application, and many applications are often on the developer's server instead of the Sina Weibo server. Therefore, cross-domain requests Data has become a major problem that developers need to solve. The majority of open platforms should implement support for JSONP. The Sina Weibo open platform does a very good job of this (although there is no description in some APIs, it can actually be used invoked in JSONP mode).

jquery ajax jsonp cross-domain call example code

Both GET and POST methods can be used to make cross-domain calls

client code

code show as below:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApp.WebForm1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<script src="jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function aa() {
        $.ajax({
            url: "http://localhost:12079/WebForm2.aspx",
            data: "p1=1&p2=2&callback=?",
            type: "post",
            processData: false,
            timeout: 15000,
            dataType: "jsonp",  // not "json" we'll parse
            jsonp: "jsonpcallback",
            success: function(result) {
            alert(result.value1);
            }
        });
    }

</script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
    <p>
        <input id="Button1" type="button" value="button" onclick="aa()" /></p>
</body>
</html>

server side code

code show as below:

 public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

           
         string callback = Request["callback"]; 
            string v1="1";
            string v2="2";
            string response = "{\"value1\":\"" + v1 + "\",\"value2\":\"" + v2 + "\"}";
            string call = callback + "(" + response + ")";
            Response.Write(call);
            Response.End();
        }
    }

The client page and server side page are in two projects for cross domain call testing.
Cross-domain example code (jquery needs to be loaded, and the page is utf-8 encoded):

code show as below:

 <!--拉勾招聘数据-->
  <script type="text/javascript">
   function success_jsonpCallback(data){
    var html = '';
    var pos = '';
    html += '<ul>';
    jQuery.each(data, function(k, v) {
                 if(k<10){
                  pos = '【' + v.city+ '】' + v.positionName + '('+ v.salary +') - '+v.companyName;
      if(pos.length > 20){
       pos = pos.substring(0,19)+'...';
                     }
                     html += '<li><a href="'+v.posiitonDetailUrl+'" target="_blank" title="【' + v.city+ '】' + v.positionName + '('+ v.salary +') - '+v.companyName+'">'+pos+'</a></li>';
                 }
    });
    html += '</ul><div class="more-link"><a href="http://www.lagou.com/jobs/list_%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91" rel="external nofollow" target="_blank"  target="_blank">更多</a></div>';
    jQuery('#lagouData').html(html);
   }

   function getLagouData() {
    jQuery.ajax({
     async:false,
     url: "http://www.lagou.com/join/listW3cplus?kd=%E5%89%8D%E7%AB%AF%E5%BC%80%E5%8F%91",
     type: "GET",
     dataType: "jsonp",
     jsonpCallback: 'success_jsonpCallback',
     contentType: "application/jsonp; charset=utf-8",
     success: function(data) {
      success_jsonpCallback(data);
     }
    });
   }
   getLagouData();
  </script>
  <div id="lagouData"></div>

jsonp code:

code show as below:

success_jsonpCallback([{"city":"广州","companyName":"POCO.CN","createTime":"15:02发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/16868.html","positionAdvantage":"身处凝聚力团队,老城区上班交通便利,双休","positionName":"商业前端开发工程师","salary":"4k-7k"},{"city":"北京","companyName":"美通云动(北京)科技有限公司","createTime":"14:47发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/16866.html","positionAdvantage":"Html5技术最棒的团队","positionName":"Web前端开发","salary":"4k-8k"},{"city":"杭州","companyName":"口袋购物","createTime":"14:42发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/13024.html","positionAdvantage":"广阔的发展平台、自我价值体现的地方","positionName":"web前端开发工程师","salary":"8k-12k"},{"city":"北京","companyName":"布丁移动","createTime":"14:02发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/1498.html","positionAdvantage":"三餐、周围美女如云","positionName":"Android开发工程师","salary":"10k-20k"},{"city":"北京","companyName":"布丁移动","createTime":"14:02发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/2539.html","positionAdvantage":"三餐,小桥流水人家,美女","positionName":"ios开发工程师","salary":"10k-20k"},{"city":"上海","companyName":"天天动听","createTime":"00:55发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/11494.html","positionAdvantage":"创业氛围 讲求小而美","positionName":"Android开发工程师","salary":"8k-16k"},{"city":"北京","companyName":"LBE安全大师","createTime":"11:39发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/5983.html","positionAdvantage":"五险一金 绩效奖金","positionName":"Android开发工程师","salary":"8k以上"},{"city":"北京","companyName":"点心移动","createTime":"11:24发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/16736.html","positionAdvantage":"技术导向的团队氛围,全方位的福利待遇","positionName":"Android","salary":"15k-25k"},{"city":"广州","companyName":"荔枝FM","createTime":"10:44发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/16634.html","positionAdvantage":"连坚持跑步、保持体重都有奖励哦!","positionName":"WP手机开发工程师","salary":"16k-25k"},{"city":"北京","companyName":"网银-京东子公司","createTime":"10:08发布","posiitonDetailUrl":"http://www.lagou.com:80/jobs/14162.html","positionAdvantage":"负责京东商城-互联网金融产品 JS开发","positionName":"Javascript 前端开发工程师","salary":"10k-20k"}])

Guess you like

Origin blog.csdn.net/cdming/article/details/130121113