Using jsonp to achieve cross-domain and the difference between json and jsonp

First, use jsonp to achieve cross-domain


1. Cross-domain issues

From a page of a website, to request Chinese content from a different website

This leads to the iframe tag: (Using the iframe tag can access the content of another page in the current page.)

<h2>我是利用iframe标签获得另一个页面</h2>
<iframe src='http://www.baidu.com'></iframe>

write picture description here

① Usage of iframe tag:
  • First, use the iframe tag to write the url corresponding to the page to be imported into the src attribute.
<iframe src='http://www.baidu.com'></iframe>
  • Second, in the script script, get the iframe element
var iframe = document.querySelector('iframe');
  • After getting the iframe element, you can find that there is a contentWindow attribute in the element and there is a document under the contentWindow.
    write picture description here
  • The obtained document element is the document document of another page, and when the document is obtained, the elements of the page can be obtained and a series of operations can be performed.
//获取iframe元素
var iframe = document.querySelector('iframe');
//iframe元素中有一个contentWindow属性
var iframeWindow = iframe.contentWindow;
//contentWindow下有一个document属性
var iframeWindowDocument = iframeWindow.document;
//获取到另一个页面的button元素
var iframeWindowDocumentBtn = iframeWindowDocument.querySelector("button");
//为iframe指定的页面的button元素添加一些样式,以作测试
iframeWindowDocumentBtn.style.backgroundColor = "red";
iframeWindowDocumentBtn.style.border = "0";
② Note:
  1. Disadvantages of iframes:

    For security reasons, the two pages must be of the same origin before using js to get the content of another page under the current page. If the origin is different, the acquisition will result in an error.

  2. Homology:

    Same-origin means: the domain name, protocol, and port are exactly the same (the same-origin policy is a browser security policy)

③ Solve cross-domain problems - (jsonp)

Since the iframe must be of the same origin before it can be processed, the cross-domain problem that occurs is solved by jsonp.

2. jsonp

① Principle:

The src attribute of the script tag supports cross-domain

② Core:
  • Only get requests can be sent (the server uses $_GET to get data)
  • The method for the server to obtain and send:
    • $_GET ['callback'] ——- (assuming the content obtained is eatFood)
    • When returned to the browser: $_GET ['callback'].'()' - splicing a bracket and returning to the browser
  • Assuming that the eatFood() obtained by the script tag of the browser will call the eatFood method in the current page, and obtain the data sent from the server.
<script>
    //定义eatFood函数
    function eatFood(foodName) {
        console.log('我被调用了哦!');
        console.log(foodName);
  }
</script>
<!-- 引入文件,并将参数callback=eatFood发送到服务器上 -->
<script src='http://192.168.43.207/Ajax%20And%20PHPLearning/23-jsonp/02-jsonp.php?callback=eatFood'></script>
 echo $_GET['callback'].'({"西红柿":"红色","黄瓜":"绿色"})';

3. The steps of using jsonp (method 1)

  • First use the src attribute of the script tag to send a get request and go to the php page
 <script type='text/javascript' src="http://192.168.43.207/Ajax%20And%20PHPLearning/23-jsonp/jsonp.php"></script>
  • And send a set of parameters to the server, such as: key is callback value is eatFood
    write picture description here
  • In the php page, the value obtained by $_GET['callback']
  • Process (such as: add parentheses - so returning to the browser is to call the eatFood function), and then return to the browser
    write picture description here
  • Since eatFood() is returned, and the eatFood function is defined in the html page, this method is called and the output result is obtained

Note: Due to the interaction of jsonp, other servers will have the same output when running this page, which is cross-domain

4. Use the $_ajax() method in jQuery to send a jsonp request (method 2)

In jQuery, a method has been encapsulated and used as a jsonp request to solve cross-domain problems.
$_ajax(), and this method will automatically splice a callback for me (default value)

① jsonpCallback (a parameter in the $.ajax() method)

This property specifies a callback function for jsonp, this value will be used to replace the random function name automatically generated by jQuery, used to let jQuery generate a unique function name

② Use the $_ajax() method to send jsonp steps:
  1. The dataType attribute value should be " jsonp ".
  2. If you want to change the data sent to the server, add the jsonCallback property, which is the data or method you want to send.
//回调函数内容
function myJsonPCallBack(data) {
    console.log('自己写的 回调函数名'+data);
}
//button按钮点击事件,发送jsonp请求
$('#jqJsonp').click(function () {
     $.ajax({
       //规定发送请求的url
       url:'03.jq_jsonp.php',
       //请求发送成功的回调函数
       success:function(data){
         console.log(data);
       },
       //设置数据类型为jsonp
       dataType:'jsonp',
       //指定回调函数
       jsonpCallback:"myJsonPCallBack"
     })
})

According to the above code, when the click event is triggered, the request will be sent to the corresponding url

And: request to send url such as:
write picture description here

=1521732451694”>http://127.0.0.1/2016-10-9/07.jsonp/03.jq_jsonp.php?callback=myJsonPCallBack&=1521732451694


Second, the difference between json and jsonp

json and jsonp are two concepts, do not confuse

① json (a data exchange format)

json is a string in some format. Basically all languages ​​have syntax for converting json strings to objects in that language.
Format:

var str = '{"name":"rose",
            "age":"18",
            "sex":"girl",
            "skill":"beautiful"
}';
//


  • JSON.parse() method - convert json string to js object in JS

Use the parse method of the JSON object to convert the json formatted string into the corresponding js object

var jsonObj = JSON.parse(str);


  • Notice:

The conversion of json-formatted strings into corresponding js objects is implemented in: registered events
ajax.onreadystatechange = function() {
  if(ajax.readyState == 4 && ajax.status == 200) {
    //json字符串 ===> js对象 
    var jsonObj = JSON.parse(ajax.responseText);
    //再使用js对象获取值,修改页面显示
    console.log(jsonObj.name);
    console.log(jsonObj.sex);
    console.log(jsonObj.age);
  }
}
② jsonp (a request method to solve cross-domain problems) json with padding

jsonp is a request method to solve cross-domain problems (different from json)

The essence is to take advantage of the cross-domain feature of the script tag.

//利用script的src属性,发送jsonp请求
<script type='text/javascript' src="http://192.168.43.207/Ajax%20And%20PHPLearning/23-jsonp/jsonp.php?callback=eatfood"></script>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325681501&siteId=291194637