Tag: Control host input call succeeds EFI UIL back comment
Solve the problem of Ajax cross-domain-JSONP principle why is there a cross-domain problem? -because there is a homologous policy
The same origin policy is a browser security policy, so-called homology refers to the request URL address of the protocol , the domain name and Port are the same, as long as one of them is not the same as the cross-domain
The origin policy is mainly to ensure the security of the browser
Browser * * Does not allow **ajax to get server data across domains under the same-Origin policy
http://www.example.com/detail.html 跨域请求: http://api.example.com/detail.html 域名不同 http://www.example.com:8080/detail.html 端口不同 http://api.example.com:8080/detail.html 域名、端口不同 https://api.example.com/detail.html 协议、域名不同 https://www.example.com:8080/detail.html 端口、协议不同
Resolving cross-domain using jquery Ajax-jsonp method calls
Although the implementation of JSONP with Ajax does not have a semi-gross money relationship ,Jsonp is through the script SRC implementation (specifically see later parsing), but the ultimate goal is to request data from the server and then callback , and for convenience, So jquery has also encapsulated Jsonp in the $.ajax method, the calling method is slightly different from the way Ajax is called, the case is as follows.
Test JQ_JSONP:
Destination request Address, http://www.jepson.com/jq_jsonp.php
<?php $c b = $_get [ ' callback ' ]; //get callback $arr = array ( = ' Zhangsan ' , ' password ' = > ' 123456 ' ); echo $CB . . Json_encode ( $arr ). ; //return callback function call //is jquery1111011117830135968942_1478857963357 ({"username": "Zhangsan", "Password": " 123456 "}); ?>
In peter.com/jq_jsonp.html, the request is made by means of the Jquery Ajax method, which is called JSONP.
<script type="Text/javascript"Src="./jquery.js"></script> <script type="Text/javascript">$( function(){$("#btn"). Click ( function(){$.ajax ({type:' Get 'Url:' http://www.jepson.com/jq_jsonp.php ', DataType:' Jsonp ', Jsonp:' Callback ',//callback function, background get receive the variable name, the default is callback //Jsonpcallback: ' abc ', callback function name, default is a long string, jquery automatically generated, in the request URL can be seen //change It doesn't matter, a little bit shorter is just a little clearer when looking at the request URL.Success function(data){Console.log (Data.username,data.password);//Zhangsan 123456}, Error: function(data){Console.dir (data); Console.log (' ERROR '); } }); }); });</script> <body> <input type="button" value= "click" id=" BTN "> </body>
As you can see, the output is ' Zhangsan 123456 '.
Note: If the background does not get the callback, return the function call work, then the error will go into the error method. This is a mistake that is often encountered at work, it is important to note that
The principle analysis of the JSONP of solving method
JSONP: Using the src attribute of the script tag for cross-domain requests, the server responds to function call arguments .
Here understand the principle of jsonp and test, need different domain , I here is Apache server , I configured two virtual host to do.
two domain code domain http://www.peter.com/, request domain http://www.jepson.com/
Jsonp Fundamentals-static method creation
Let's look at the basic principles of JSONP to solve cross-domain problems by testing the static method created below
- Test 1:
目标请求地址,http:/www.jepson.com/1.php
<?php echo"1;"; ?>
在 peter.com/1.html 里面,通过 script标签进行请求
<script type="text/javascript" src="http://www.jepson.com/1.php"></script>
Open F12, go to the network, find the 1.php request, check Response, found that the result is 1, cross-domain request is so successful! Yes, that's the simple principle.
But have you found that we are unable to obtain this request to the data, how to do?
The script tag is loaded synchronously by default, so we echo ' var a = 1; ' , get it ' var a = 1; 'is that what you can think of as declaring a variable and assigning a value?
And because it is synchronous, so the next script statement is not able to use this a? Let's give it a try.
- Test 2:
目标请求地址,http:/www.jepson.com/2.php,就一行
<?php echo"var a = 1;"; ?>
In peter.com/2.html, request via script tag
<!--can I understand that a variable is declared here? var a = 1 ; --<script type = src = "http://www.jepson.com/2.php" ; </script ; script type = " Text/javascript "; Console.log (a); //1 </script ;
F12 Open the console, no mistake! You output A, the value of the output is 1, we got the data in the background transfer
However, this static way obviously has a lot of drawbacks, first put on the top of the code, or the following can not be used to return the data
Secondly, this kind of static method of parameter configuration is inconvenient, so we generally use the dynamic creation of the script tag , add to the head, and with parameters
Jsonp Fundamentals-Dynamic Method creation
dynamic creation of the script tag , added to the head, and with parameters, you can solve the Jintai
- Test 3:
目标请求地址,http:/www.jepson.com/3.php,就一行
<?php echo"var a = 1;"; ?>
在 peter.com/3.html 里面,通过 script语句动态创建 script标签进行请求
<script type="text/javascript"> var script = document.createElement(‘script‘); ‘http://www.jepson.com/3.php‘; var head = document.getElementsByTagName(‘head‘)[0]; head.appendChild(script); console.log( a ); </script>
Open F12, shocking thing happened, * * unexpectedly error , **uncaught referenceerror:a is not defined (...) ?? A variable is not defined?
We open the network, find 1.php this request, point open response, found that there is ' var a = 1; ', the request succeeded? What's the situation?
Note : The original script is dynamically created in a way that sends the request asynchronously , although the request succeeds, but when the variable is used, the request is not completed, which is equivalent to not defining the variable , and then the error is made.
So what? Here's a little tip that we can Echo ' foo (123) '; This is equivalent to the request completed Foo (123), that is, call our code foo function, we write a function in code foo (data) {Console.log (data), this is equivalent to a callback, we get the data. The following is a code demonstration.
Test 4:
Destination request Address, http:/www.jepson.com/4.php
<?php echo‘foo(123)‘; ?>
In peter.com/4.html, create a script tag to request it dynamically through the script statement
<script type="text/javascript"> var script = document.createElement(‘script‘); ‘http://www.jepson.com/4.php‘; var head = document.getElementsByTagName(‘head‘)[0]; head.appendChild(script); function foo(data){ console.log( data ); //foo(123) 对 foo 调用 输出 123 } </script>
F12 can see the output 123, and view the request in the network, response can see is foo (123)
Then we can use this dynamic way very easy to get the background data, but the foreground declaration and the function name of the background call need the same line, such as the above Foo, so it is not very good, every change, it will have to butt a bit.
so we can put the callback function name in the parameters of the transmission . The cases are as follows:
Test 5:
Destination request Address, http:/www.jepson.com/5.php
<?php $CB = $_get [ ' callback ' ]; //get function name by callback key $arr = array ( = ' Zhangsan ' , ' password ' = > ' 123456 ' ); //we can also pass a bit more complex data echo $CB . . Json_encode ( $arr ). ; //Hello (Json_encode ($arr)) ?>
In peter.com/5.html, create a script tag to request it dynamically through the script statement
<script type="Text/javascript"> function Hello(data){Console.log (data);//Object {username: "Zhangsan", Password: "123456"}Console.log (Data.username);//ZhangsanConsole.log (Data.password);//123456}varScript = Document.createelement (' script '); SCRIPT.SRC =' Http://jepson.com/5.php?callback=hello ';varHead = document.getElementsByTagName (' head ')[0]; Head.appendchild (script);</script>
* * Summary: The essence of **JSONP: Dynamically create a script tag, and then send cross-domain requests through its SRC attribute, then the data format of the server-side response is "function call", so you must declare a function before sending the request, and the name of the function is identical to the name passed in the argument. The function declared here is called by the contents of the server response (which is actually a function call JS code). JSONP is a protocol.
Simple Package
above is the whole principle of JSONP , the following is the implementation of the jquery Ajax JSONP Way of the simple package , interested can refer to.
function ajax(obj){ //default parameter because the JSONP principle is passed in the URL body, //So only get is supported, so the type is not configured vardefaults = {URL:' # ', DataType:' Jsonp ', Jsonp:' Callback ', data: {}, Success: function(data) {Console.log (data)}}//processing parameters, passing functions, overriding default arguments, using default parameters without passing them for(varKeyinchobj) {defaults[key] = obj[key]; }//Here is the default callback function name, generated based on the current date and random number varCBName =' JQuery '+ (' 1.11.1 '+Math. Random ()). Replace (/\d/g,"") +' _ '+ (New Date(). GetTime ());//Get rid of all the dots, the equivalent of jquery followed by a string of numbers _ Plus time numbers if(Defaults.jsonpcallback) {cbname = Defaults.jsonpcallback; }//This is the callback function, call mode: Server response content to invoke //Adds a method to the Window object, the method name is the value of the variable cbnamewindow[CBName] = function(data){Defaults.success (data);//The success data here is the actual argument}//The data of the parameter is processed and added to the SRC URL varparam ="'; for(varattrinchDefaults.data) {param + = attr +' = '+ defaults.data[attr] +' & '; }if(param) {//Remove the last one ¶m = param.substring (0, param.length-1); param =' & '+ param; }//Dynamic Add script tag, configuration parameters varScript = Document.createelement (' script ');//DEFAULTS.JSONP background get variable name, CBName callback function name, param variableSCRIPT.SRC = Defaults.url +'? '+ Defaults.jsonp +' = '+ CBName + param;varHead = document.getElementsByTagName (' head ')[0]; Head.appendchild (script); }
Solving Ajax cross-domain problem--JSONP principle analysis