Homologous strategy
Balabalabala (the definition doesn't need to be mentioned, simply speaking, the protocol, port and domain name should be the same.)
Note: the difference caused by protocol and port is not within the scope of front-end solution
JSONP
The principle of jsonp is very simple. It is to create script tags dynamically, and then use script src to get data across domains without the restriction of homology policy.
First step
Dynamic creation
var script = document.createElement("script");
script.src = "https://api.douban.com/v2/book/search?q=javascript&count=1&callback=handleResponse";
document.body.insertBefore(script, document.body.firstChild);
Here, we use the Douban api to realize data interaction
The second step
In the page, the returned JSON is passed into the callback function as a parameter, and we use the callback function to operate the data.
function handleResponse(response){
// Operation code for response data
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JSONP Implement cross domain 2</title>
</head>
<body>
<div id="mydiv">
<button id="btn">click</button>
</div>
</body>
<script type="text/javascript">
function handleResponse(response){
console.log(response);
}
</script>
<script type="text/javascript">
window.onload = function() {
var oBtn = document.getElementById('btn');
oBtn.onclick = function() {
var script = document.createElement("script");
script.src = "https://api.douban.com/v2/book/search?q=javascript&count=1&callback=handleResponse";
document.body.insertBefore(script, document.body.firstChild);
};
};
</script>
</html>
jQuery encapsulates JSONP
The cross domain code reference realized by $. ajax of jQuery is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery Realization JSONP</title>
</head>
<body>
<div id="mydiv">
<button id="btn">click</button>
</div>
</body>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
$(function(){
$("#btn").click(function(){
$.ajax({
async : true,
url : "https://api.douban.com/v2/book/search",
type : "GET",
dataType : "jsonp", // Data type returned, set to JSONP mode
jsonp : 'callback', //Specify a query parameter name to override the default JSON callback parameter name callback
jsonpCallback: 'handleResponse', //Set callback function name
data : {
q : "javascript",
count : 1
},
success: function(response, status, xhr){
console.log('The state is:' + status + ',The state is:' + xhr.statusText);
console.log(response);
}
});
});
});
</script>
</html>
Through $. getJSON()
Use getJSON to implement, as long as the callback =? Parameter is added to the address, the reference code is as follows:
$.getJSON("https://api.douban.com/v2/book/search?q=javascript&count=1&callback=?", function(data){
console.log(data);
});