Javascript : How to get value of variable from specific file from 2 different file?
我有一个页面从另一个服务器加载JS文件。它为电子商务商店中的每个产品加载文件,其ID在URL中,请参见下面的结构。
产品1:http://static.www.xxx.com/mydata/uxkojyed9wxfpaasite/v4_3/1/d/itemjs
产品2:
http://static.www.xxx.com/mydata/uxkojyed9wxfpaasite/v4_3/2/d/itemjs
产品3:
http://static.www.xxx.com/mydata/uxkojyed9wxfpaasite/v4_3/3/d/itemjs
所有JS文件都包含如下代码
1 | var MyItemData={"counts":{"q":1,"a":1,"r":2,"ar":4,"rr":0,"dq":1,"da":1,"c":0,"sdsd":0},"active":true}; |
现在我正在用HTML阅读这些数据,如下所示
1 2 3 | var mycounta = MyItemData.counts.a; var mycountq = MyItemData.counts.q; var mycountr = MyItemData.counts.r; |
这里的问题是,我只能获取上一个产品的数据,因为变量
可以循环下面的答案,动态加载外部JS文件。
如何动态加载javascript文件?
在每次迭代中,读取
在上述链路上使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <script type="application/javascript"> var listOfJSFiles=["http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/1/d/itemjs","http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/2/d/itemjs","http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/3/d/itemjs"]; var listOfMyItemData=[]; function loadJS(file) { // DOM: Create the script element var jsElm = document.createElement("script"); // set the type attribute jsElm.type ="application/javascript"; // make the script element load file jsElm.src = file; // finally insert the element to the body element in order to load the script document.body.appendChild(jsElm); } var arrayLength = listOfJSFiles.length; for (var i = 0; i < arrayLength; i++) { loadJS(listOfJSFiles[i]); listOfMyItemData.push(MyItemData); //removing listOfJSFiles[i] from html is recommended. } |
前提是要使用
1 2 3 4 | var items = [], addItem = function() { items.push(MyItemData) }; |
然后在每个脚本后调用
1 2 3 4 5 6 7 8 9 10 11 12 13 | <script src="http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/1/d/itemjs" > addItem() <script src="http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/2/d/itemjs" > addItem() |
等。