The idea of JSONP is very simple.
- Front-end Create script tag, set SRC, add to head (you can add to body)
- Backstage returns a JS variable Jsonp, this JSONP is the JSON data after the request
- Delete the script tag when the callback is complete (there are some cleanup tasks such as avoiding some browser memory leaks, etc.)
Interface
12345 |
Sjax.load( url, // 跨越请求的URL success, // 回调函数,必须定义一个形参,用于接收后台返回的全局变量jsonp (约定后台返回如jsonp = {...}结构) timestamp, // 传true会加一个时间戳,防止缓存,默认不加 ); |
Example:
12345678910111213141516171819202122 |
<!DOCTYPE HTML>
<meta charset=
"utf-8"
>
<title>sjax_0.1.js by snandy</title>
<script src=
"http://files.cnblogs.com/snandy/sjax_0.1.js"
></script>
<body>
<p id=
"p1"
style=
"background:gold;"
></p>
<input type=
"button"
value=
"Get Name"
onclick=
"clk()"
/>
<script type=
"text/javascript"
>
function
clk(){
Sjax.load(
‘http://files.cnblogs.com/snandy/jsonp.js‘
,
function
(){
document.getElementById(
‘p1‘
).innerHTML =
‘Hi, ‘
+ jsonp.name;
}
);
}
</script>
</body>
|
This HTML implementation of a simple front and back interactive function, click the button "Get Name", get to Name after the show on the paragraph p.
The Sjax.load method is called in the CLK function, and S in Sjax is the script. I used the Ajax name in my Ajax series, and here we use Sjax.
The requested background URL is jsonp.js, which returns the following
Because it is a test, it is implemented in the simplest way. The background of the request actually does not have to be the JS file, can be php,java and so on any background language, they may connect the database to carry on a series of business query. In short, it must return the structure of the variable JSONP, this variable is a JS object, as to how complex there is no need to pay attention to.
Jsonp for cross-domain access