Using script's SRC to achieve cross domain and ajax like effects

  • 2020-03-30 04:16:45
  • OfStack


If you have two servers with different domain names, and, you can get some data at Of course, if it's a page, you can use ajax to request the interface directly, but if it's a page on, you can request it directly.

B_return_js.php interface code:

$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 of, it will directly return json_encode($a). However, if we want to use SRC attribute to implement cross-domain, we need to assign this value to a js variable to ensure that we can get this data and use it in the page after the script tag is loaded. < br / >

Simple implementation

An easy way to do this is on the page under, directly

<script src=""></script>

In this way, the data returned from this interface can be obtained directly from the page of
However, there is a drawback, this data can only be obtained when the page is loaded, if we want to use ajax to be able to obtain new interface data at any time, such as click a button to get data local refresh from this interface, this way is not suitable.

Kind of ajax

The idea of implementing the ajax-like approach described above is to regenerate the tag when the ajax condition is triggered to retrieve the data from the interface again, but it's still a bit of a challenge (at least for me).

The code:

Suppose there is a button under the page

< Input type="button" id="ajax_request_from_b" value=" request from "/>
Each click will fetch data from the interface.

function createScript()
    ele.src = '';
    ele.type = 'text/javascript';
    ele.language = 'javascript';
} function getData()
} $('#ajax_request_from_b').click(function(){     //The script tag needs to be reloaded each time, so a new script script & NBSP; is generated each time.                 The signature is guaranteed to fetch data
from a cross-domain server     if(ele && ele.parentNode)
        //ele.parentNode.removeChild(ele);  // This deletion cannot be made ele Completely removed from memory, just removed in dom The position of
        for (var property in ele) {           
            delete ele[property];        //Delete
completely          }
    ele = document.createElement('script'); //This is a new ele
    ele.onload = function(){getData()};  //Userdata can be obtained after script elements are loaded, and the user information
is acquired in random order every time });

So every time you click a button, you get the data from the interface all over again, which is similar to ajax, but it's a cross-domain approach to js implementation, which is a bit thankless, but a good way to think about it.

Related articles: