Jsonp for cross-domain access

Source: Internet
Author: User

The idea of JSONP is very simple.

    1. Front-end Create script tag, set SRC, add to head (you can add to body)
    2. Backstage returns a JS variable Jsonp, this JSONP is the JSON data after the request
    3. 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">    functionclk(){        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

1 jsonp = {name:‘jack‘};

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.