2017-08-01 55 views
1

我想將整個JSON對象傳遞給動態HTML元素。動態HTML元素中的多個JSON或JavaScript對象

this example

類似我用下面的代碼來實現這一功能 -

btoa(unescape(encodeURIComponent(JSON.stringify(dataItem)))) // To escape special characters and encode JSON 

'<p><a href="#" onclick="passJson(\'' + dataItem + '\')">Check console log</a></p>'; 

JSON.parse(atob(obj)) // to decode back to JSON 

上面的例子之前,我正在this example讓我的日子苦不堪言。

最後一個例子只有一個大問題,即所有鏈接都指向由以下代碼生成的最後一個對象。

for(var i = 0; i < giveData().length; i++){ 
    var dataItem = giveData()[i]; 
    dataItem["name"] = dataItem["name"] + i; 
    dataItem["value"] = i; 

    var dataItem = btoa(unescape(encodeURIComponent(JSON.stringify(dataItem)))) 

    var divStr='<p><a href="#" onclick="passJson(\'' + dataItem + '\')">Check console log</a></p>'; 

    htmlStr += divStr; 
} 

我相信這是由於相同的變量名dataItem(它進來HTML裏面passJson())。

在創建/更新變量divStr時,在將其追加到body之前,它必須取最後一個值dataItem變量。

var divStr='<p><a href="#" onclick="passJson(dataItem)">Check console log</a></p>'; 

1.你能提final example的改進選項(S),如果有/任何?我擔心這種解決方法不適用於更大的JSON對象。

2.另外,我在initial example中做了什麼錯誤?

I don't想使用attributelike this。 而我don't想要在HTML中傳遞字符串化的JSON對象。

不用擔心giveData()被多次調用。我很懶,同時也不想全局數組變量。

謝謝。

+0

好了,它正在爲[複雜JSON(http://jsfiddle.net/sujit77/6LzCA/112/)的對象,但我還是想知道更好soulution。 –

回答

0

我想你會永遠得到最後一個項目的所有點擊。你可以檢查添加項目到另一個item.Also var dataItem = giveData()[i];將再次調用不好的功能。在for循環giveData().length也將調用相同的函數,所以嘗試初始化變量的GiveData(),然後使用它和不要調用該函數。還有一件事是因爲您有對象數組,您可以選擇forEach.Or讓我們知道你想通過這樣做來達到目的。

 var arrayObj= [{"context":{"dialog":{},"suggestions":["confusion","Were you looking for this?",[{"name":"Claim ratio","iid":"dkjw343-efkn3-34klffd"}]],"user":{"designation":"FLS","client_iid":1,"channel":"BANCA","name":"Sujit","dashboard_iid":1},"namespace":"sales"},"conversation_metadata":{"preprocessed_utterance":"solvency percentage","updated_context":{"dialog":{},"suggestions":["confusion","Were you looking for this?",[{"name":"Claim ratio","iid":"dkjw343-efkn3-34klffd"}]],"user":{"designation":"FLS","client_iid":1,"channel":"BANCA","name":"Sujit","dashboard_iid":1},"namespace":"sales"},"matching_intent":"fallback-intent","top_matches":[["dkjw343-efkn3-34klffd",0.4999999999999999,{"final_vector":{"solvency":1,"percentage":1},"concepts_interchanged":[],"concept_vector":{"percentage":1,"claim":1},"unknown_concept_query":[],"optional_concept":[],"question":"Claim ratio","weights":[["percentage",0.7071067811865475,1]]}],["jd34jn-43jn3-3kjnewd",0,{"final_vector":{"solvency":1,"calculate":1},"concepts_interchanged":[["calculate","percentage"]],"concept_vector":{"commission":1,"agent":1},"unknown_concept_query":[],"optional_concept":[],"question":"Agent commission","weights":[]}]],"status":"SUCCESS","time":0.020668506622314453},"end_time":"Fri, 28 Jul 2017 07:47:48 -0000","iid":"djnfdk-32n23nkjnk-23nkkjkjd","matched_query":"fallback-intent","flag":"DISLIKE","status":"SUCCESS","start_time":"Fri, 28 Jul 2017 07:47:48 -0000","response":[{"type":"text","content":"Sorry, I am unable to answer your query!","version":"0.0.0","interface":"web"}],"query":"solvency ratio","confidence":0.4999999999999999},{"context":{"dialog":{},"user":{"designation":"FLS","client_iid":1,"channel":"BANCA","name":"Sujit","dashboard_iid":1},"auto_suggest_selection":"dkjw343-efkn3-34klffd","previous_intent":"dkjw343-efkn3-34klffd","namespace":"sales"},"conversation_metadata":{"preprocessed_utterance":"claim percentage","updated_context":{"dialog":{},"user":{"designation":"FLS","client_iid":1,"channel":"BANCA","name":"Sujit","dashboard_iid":1},"auto_suggest_selection":"dkjw343-efkn3-34klffd","previous_intent":"dkjw343-efkn3-34klffd","namespace":"sales"},"matching_intent":"dkjw343-efkn3-34klffd","top_matches":[],"status":"SUCCESS","time":0.016078472137451172},"end_time":"Fri, 28 Jul 2017 07:47:52 -0000","iid":"sdlkmcllksd-23knlsd-32emmll32","matched_query":"dkjw343-efkn3-34klffd","flag":"CLEAR","status":"SUCCESS","start_time":"Fri, 28 Jul 2017 07:47:52 -0000","response":[{"type":"text","content":"Claim Settlement Ratio = Total Claims Approved (paid to nominees) divided by Total Claims Received by the Company.\nThe overall company claim ratio was 95% as on 2015-16.\nFor more specific claim ratios, please contact the claims team.\n","version":"0.0.0","interface":"web"}],"query":"Claim ratio","confidence":1}]; 

     var htmlStr = ''; 

     function passJson(obj) { 
      console.log(JSON.parse(atob(obj))); 
     } 
     arrayObj.forEach(function(dataItem){        
      var dataItem = btoa(unescape(encodeURIComponent(JSON.stringify(dataItem)))) 

      var divStr='<p><a href="#" onclick="passJson(\'' + dataItem + '\')">Check console log</a></p>'; 

      htmlStr += divStr; 
     });    
     $('body').append(htmlStr); 
+0

我知道有人會指出這一點(現在補充問題)。我很懶,不想要全局數組變量。但功能保持不變。 –

+0

我有兩個問題 - ** 1。如果有[有最終例子](http://jsfiddle.net/sujit77/6LzCA/111/),有沒有任何改進的選擇?**不包括如何調用'giveData()'的方式。 **與將JavaScript對象傳遞給HTML的更好方法有關** ** 2。我在[初始示例](http://jsfiddle.net/sujit77/6LzCA/110/)中做了什麼錯誤?** –

+0

1。是的,但這取決於你想要改進什麼樣的方式[owasp-esapi-js](https://github.com/ESAPI/owasp-esapi-js)2.你的** dataItem **將會有當它到達** $('body')時的最後一個值。append(htmlStr); **你的** htmlStr **仍然有** dataItem **作爲它的一部分。你可以檢查[Template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) – Amit