2017-06-01 72 views
1

我有1頁從另一個服務器加載Js文件。其電子商務中每個產品的加載文件存儲在URL中的標識符見下面的結構。Javascript:如何從2個不同文件的特定文件中獲取變量的值?

產品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文件包含代碼象下面

var MyItemData={"counts":{"q":1,"a":1,"r":2,"ar":4,"rr":0,"dq":1,"da":1,"c":0,"sdsd":0},"active":true}; 

現在我在這裏讀的HTML這個數據像下面

var mycounta = MyItemData.counts.a; 
    var mycountq = MyItemData.counts.q; 
    var mycountr = MyItemData.counts.r; 

問題是,我只能得到的數據,去年產品可變MyItemData是所有文件的相同。我必須閱讀每個文件的ID,但我不知道適當的方式來實現它。有沒有人嘗試過這樣的事情?

回答

1

您可以循環低於加載外部JS文件動態的答案。

How do I load a javascript file dynamically?

在每次迭代中,讀MyItemData並使用它。

在上面的鏈接上使用函數loadJS;

<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. 
} 

</script> 
+0

文件已在頁面上加載。但是'MyItemData'只從最後一個文件獲取數據。我已經循環加載每個產品的文件。 – Kul

+0

編輯回覆。 –

+0

太棒了。其作品! – Kul

1

只要您使用script標記加載這些文件即可。您可以創建一個數組來保存項目,並使用內聯腳本混合腳本標記,從而將當前值MyItemData保存在數組中。

<script> 
    var items = [], 
     addItem = function() { 
      items.push(MyItemData) 
     }; 
</script> 

然後調用addItem每個腳本後或onload事件打(不知道以後會工作)。

<script 
src="http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/1/d/itemjs" 
> 
</script> 

<script>addItem()</script> 

<script 
src="http://static.www.xxx.com/mydata/uXKojYEd9WXFpAasite/v4_3/2/d/itemjs" 
> 
</script> 

<script>addItem()</script> 

+0

不幸的是它只給出最後一個文件的數據 – Kul

+0

@Kul您是否在使用'items'來訪問您的數據? –

相關問題