简体   繁体   English

使用AJAX在两个JavaScript文件之间进行通信并发送数据

[英]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. 我可以从B.js文件内的Ajax调用的成功功能访问外部JavaScript文件A.js。 Here is the code from B.js file. 这是B.js文件中的代码。

$.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. 现在,我想在上述AJAX调用中将数据发送到A.js,但不使用data属性。 I don't want it to be appended to URL. 我不希望将其附加到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. 我只想发送在B.js文件中获得的内容,然后将其发送到A.js文件进行处理。 How do I achieve this? 我该如何实现? Any help is appreciated. 任何帮助表示赞赏。 Thank You. 谢谢。

Here is my simple A.js file. 这是我简单的A.js文件。

$("#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. 我希望上面的函数在单击链接时运行,以从B.js文件中的AJAX调用中获取该链接的值。

You should declare a global variable global_data for example and then assign the data to it before loading your A.js script 例如,您应该声明一个全局变量global_data ,然后在加载A.js脚本之前将数据分配给它

//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: 不要使用AJAX来检索您的A.js文件,而是使用<script>标记将其插入您的页面,如下所示:

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: jQuery示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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