Home >Web Front-end >JS Tutorial >Use script's src to achieve cross-domain and ajax-like effects_javascript skills
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:
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
In this way, the data returned by this interface can be directly obtained on the a.com page.
But there is a flaw here. This data can only be obtained when the page is loaded. If we want to use ajax to obtain new interface data at any time, it is not suitable. For example, click a button to obtain it from this interface. Partial data refresh, this method is somewhat inappropriate.
Ajax-like implementation
In fact, the idea of implementing the above-mentioned ajax-like is to regenerate the above tag when the ajax condition is triggered, so as to obtain data from the interface again, but in fact it is still slightly difficult to implement (at least for me It took a lot of effort).
Upload code:
Suppose there is a button under the a.com/scriptSrc.php page
Each click will obtain data from the b.com/b_return_js.php interface, similar to ajax implementation code:
function getData()
{
console.log(userdata);
}
$('#ajax_request_from_b').click(function(){
//This script tag needs to be reloaded every time, so a new script tag must be regenerated every time to ensure that data can be obtained from the cross-domain server
If(ele && ele.parentNode)
{
//ele.parentNode.removeChild(ele); //This kind of deletion cannot completely delete ele from the memory, but only removes its position in the dom
for (var property in ele) {
delete ele[property]; delete ele[property];
}
}
ele = document.createElement('script'); //This is a new ele
CreateScript();
Document.getElementsByTagName("head")[0].appendChild(ele);
ele.onload = function(){getData()}; // Userdata can be obtained after the script element is loaded. Each time, user information is obtained in random order
});