简体   繁体   English

动态HTML元素中的多个JSON或JavaScript对象

[英]Multiple JSON or JavaScript objects in dynamic HTML elements

I want to pass entire JSON object to dynamic HTML elements. 我想将整个JSON对象传递给动态HTML元素。

Similar to this example 类似于这个例子

I used following codes to achieve this functionality - 我使用以下代码来实现此功能-

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

Before above example, I was working on this example to make my day miserable. 在上面的示例之前,我正在尝试制作此示例,以使我的一天痛苦不堪。

Last example has only one and big issue that all links are refering to last object generated by following code. 最后一个示例只有一个大问题,即所有链接都引用由以下代码生成的最后一个对象。

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

I believe this is due to same variable name dataItem (which comes in HTML inside passJson() ). 我相信这是由于相同的变量名dataItem (在passJson()中的HTML中)造成的。

While creating/updating variable divStr , it must be taking last value of dataItem variable before appending it to body. 在创建/更新变量divStr ,在将其附加到主体之前,它必须采用dataItem变量的最后一个值。

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

1. Can you mention option(s) of improvement in final example if there is/are any? 1.如果有,您能否在最后的示例中提及改进选项? I am worried that this workaround will not work for bigger JSON objects. 我担心这种解决方法不适用于较大的JSON对象。

2. Also, what mistake I was doing in initial example ? 2.另外,我在最初的示例中犯了什么错误?

I don't want to use attribute like this . don't希望使用attribute 这样 And I don't want to pass stringified JSON object in HTML. 而且我don't在HTML中传递字符串化的JSON对象。

Don't worry about giveData() being called multiple times. 不必担心giveData()被多次调用。 I was lazy and at same time didn't wanted global array variable. 我很懒,同时又不想全局数组变量。

Thank you. 谢谢。

I guess you will always get last item for all click. 我想您总会获得所有点击的最后一项。 you can check for adding item into another item.Also var dataItem = giveData()[i]; 您可以检查是否将项目添加到另一个项目中。另外, var dataItem = giveData()[i]; will again call the function which is not good.and same in for loop giveData().length will also call the same function agian so try to initialize giveData() with a variable and then use it and not call the function.One more thing as you have arrays of object you can opt for forEach.Or let us know what you want to achieve by doing this. 会再次调用不好的函数。for循环中的相同giveData().length也将调用相同的函数agian,因此尝试使用变量初始化GiveData()然后使用它而不调用函数。当您有对象数组时,可以选择forEach。或者让我们知道您要通过此方法实现的目标。

        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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM