1.jsonp understanding
Because cross-domain and can not get the browser sends ajax request normal data, and the data is sent when a request script tag is http request, no cross-domain problem. Using this mechanism to bypass the cross-domain limits for technical back-end data call jspnp
The principle:
a function defined at the client, this function is usually passed parameters (data) to render the page.
To request the data, create a script tag, the src attribute set. src attribute value included in the function name defined by the client, and the data to be passed to the server of
the server receives the request sent by the script tag returns a file js. Contents of this file is to call the client-defined function, passing the arguments, thus disguised request to the data
2. Native js achieve jsonp
html page code
<body>
<h1>新闻标题</h1>
<p>内容</p>
<input type="button" value="更新信息" id="btn">
</body>
<script>
function updatePage(obj){
var h1 = document.querySelector("h1")
var p = document.querySelector("p")
h1.innerHTML = obj.title
p.innerHTML = obj.content
}
//监听按钮点击
document.querySelector("#btn").onclick = function(){
//创建script标签
var script = document.createElement("script")
//设置src属性
script.src = "/jsonp/index.js"
// 插入标签
document.head.appendChild(script)
// 移除此标签
document.head.removeChild(script)
}
</script>
Js file code returned by the server
updatePage({
title:"火影忍者完结了",
content:"宇智波鼬的须佐能乎是最早登场的,虽然不是完全体状态,但鼬的须佐手持三大神器,可谓攻守兼备,让敌人找不到任何破绽。"
})
Here write server-side code is dead, the actual project, will return to the front end of the data transfer based on dynamically generated js code, but are essentially calling client functions
such as: src format should be like this
localhost:8080/jsonp?cb=updatePage&id=1
So that the server knows the function js file returned to call is updatePage, and the argument is based on data acquired id values to the database and passed into the updatePage
3.jquery achieve
Using $ .ajax (), passing configuration items
<script>
function updatePage(obj){
var h1 = document.querySelector("h1")
var p = document.querySelector("p")
h1.innerHTML = obj.title
p.innerHTML = obj.content
}
//监听按钮点击
$("#btn").on("click",function(){
console.log("click")
$.ajax({
url:"./jsonp/index.js",
type:"get",
dataType: "jsonp",
data:{
id:1
},
jsonp:"cb",// 要调用的客户端函数的key
jsonpCallback:"updatePage",//客户端函数名称
success:function(data){
console.log(data)
}
})
})
</script>
Run code to access the url
http://localhost:8080/jsonp/index.js?cb=updatePage&id=1