我可以从B.js文件内的Ajax调用的成功功能访问外部JavaScript文件A.js。 这是B.js文件中的代码。
$.ajax({
url:"A.js"
}).done(function(){
alert("Success");
}).fail(function(){
alert("Failure");
});
我收到警报“成功”。 现在,我想在上述AJAX调用中将数据发送到A.js,但不使用data属性。 我不希望将其附加到URL。 我只想发送在B.js文件中获得的内容,然后将其发送到A.js文件进行处理。 我该如何实现? 任何帮助表示赞赏。 谢谢。
这是我简单的A.js文件。
$("#bookLink").click(function(){
console.log();
});
我希望上面的函数在单击链接时运行,以从B.js文件中的AJAX调用中获取该链接的值。
例如,您应该声明一个全局变量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");
});
不要使用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示例:
$.getScript('/path/to/A.js', function (script) {
// fired once the script has been loaded (but not necessarily executed).
});