Home  >  Article  >  Web Front-end  >  Use script's src to achieve cross-domain and ajax-like effects_javascript skills

Use script's src to achieve cross-domain and ajax-like effects_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:31:531558browse

Scene

If there are two servers with different domain names, a.com and b.com, you can get some data in the interface b.com/b_return_js.php. Of course, if it is on the page of b.com, you can use ajax to directly request this interface, but what if it is requested on the page of a.com.

Interface code of b_return_js.php:

Copy code The code is as follows:

$a = array(
array('username'=>'tony', 'age'=>25),
Array('username'=>'yimeng', 'age'=>23),
array('username'=>'ermeng', 'age'=>22),
array('username'=>'sanmeng', 'age'=>21),
);
shuffle($a);

echo 'var userdata = '.json_encode($a).';'; //Generally, if it is an in-site request from b.com, json_encode($a) will be returned directly, but if you want to use the src attribute to achieve cross-domain , here we need to assign this value to a js variable to ensure that this data can be obtained and used in the page after the script tag is loaded.

Simple implementation

There is a simple way to go to the page under a.com directly

Copy code The code is as follows: