简体   繁体   中英

Communicate between two JavaScript files using AJAX and send data

I am able to reach an external JavaScript file A.js from success function of an Ajax call within B.js file. Here is the code from B.js file.

$.ajax({
    url:"A.js"
}).done(function(){
    alert("Success");
}).fail(function(){
    alert("Failure");
});

I receive alert "Success". Now I want to send data within the above AJAX call to A.js but without using data attribute. I don't want it to be appended to URL. I just want to send something which I have obtained in the B.js file and send it for processing to A.js file. How do I achieve this? Any help is appreciated. Thank You.

Here is my simple A.js file.

$("#bookLink").click(function(){
    console.log();      
});

I would like this above function, which runs on click of a link, to get value of that link from the AJAX call in B.js file.

You should declare a global variable global_data for example and then assign the data to it before loading your A.js script

//global variable
window.global_data = 'some data';
$.ajax({
    url:"A.js"
}).done(function(){
    //use the variable on script load
    alert(global_data);
}).fail(function(){
    alert("Failure");
});

Instead of using AJAX to retrieve your A.js file, insert it into your page with a <script> tag like so:

var script = document.createElement('script');
script.src = '/path/to/A.js';
script.onload = function () {
    // this will execute when your "A.js" script is loaded into
    // your environment - "A.js" will have the same global
    // object (window) as your "B.js"
}

document.body.appendChild(script);

jQuery example:

$.getScript('/path/to/A.js', function (script) {
    // fired once the script has been loaded (but not necessarily executed).
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM