我正在尝试为我们正在使用的一套应用程序加载一个共享头。目前,我可以拉入HTML文件,甚至可以执行javascript。
$("#header-container")
.load("http://component.balanceinnovations.dev/header.html header", function () {
$.getScript("http://component.balanceinnovations.dev/js/header.js");
});这很好用,但是我想给header.js传递一个参数。所以我试着这样做
$("#header-container")
.load("http://component.balanceinnovations.dev/header.html header", function () {
$.get("http://component.balanceinnovations.dev/js/header.js", { cityID: '4274356' }, undefined, 'script');
});在header.js中,如何引用此参数?如果有可能的话。
发布于 2016-03-30 06:28:43
通过使用$.get(url,成功),您正在请求从您的服务器加载JavaScript文件。不能在脚本中传递参数。
你可以这样做。
var cityID = 4274356;
$("#headercontainer").load("http://component.balanceinnovations.dev/header.html header", function () {
$.getScript( "http://component.balanceinnovations.dev/js/header.js", function( data ) {
//once download was performed then here you can pass your parameters into header.js.
});
});编辑:
在使用IIFE的情况下,您可以在加载header.js之前定义一个全局变量,并如下所示更改您的函数。
(function(cityID) {
// cityID == 4274356'
})(cityID);发布于 2016-03-30 06:02:48
这似乎是可能的。根据jQuery's website的说法,$.getScript函数“是一个简写的Ajax函数,相当于...”(请参阅下面的$.ajax代码)。您必须使用$.ajax函数将数据传递给服务器。通过将Ajax page中的数据属性添加到getScript page上的$.ajax示例中,它应该如下所示...
$.ajax({
url: "http://component.balanceinnovations.dev/header.html",
data: { cityID: '4274356' },
dataType: "script",
success: successFn
});
function successFn(data) {
$("#header-container").html(data);
}https://stackoverflow.com/questions/36295592
复制相似问题