Use src of script to implement cross-origin and ajax-like effect _ javascript skills

Source: Internet
Author: User
There are multiple methods to solve the cross-origin issue of JavaScript, one of which is to use the src attribute of the script tag, because this attribute is not subject to domain name restrictions, we can directly direct the src link to an interface of a cross-origin website. This interface returns js Code or json data to obtain data across domains. Scenario

If there are two servers with different domain names, a.com and B .com, some data can be obtained from the B .com/ B _return_js.php interface. Of course, if it is a B .com page, you can use ajax to directly request this interface, but if it is a request on the.com page.

B _return_js.php interface code:

The Code is as follows:


$ A = array (
Array ('username' => 'Tony ', 'age' => 25 ),
Array ('username' => 'imeng', 'age' => 23 ),
Array ('username' => 'ermeng', 'age' => 22 ),
Array ('username' => 'sanmeng', 'age' => 21 ),
);
Shuffle ($ );

Echo 'var userdata = '. json_encode ($ ). '; // generally, if it is a B .com site request, json_encode ($ a) is returned directly, but if you want to use the src attribute to implement cross-origin, here, we need to assign this value to a js variable to ensure that the data can be obtained and used on the page after the script tag is loaded.

Simple implementation

A simple method is to directly

The Code is as follows:


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.