根据json内容填充字段

时间:2015-03-07 16:57:50

标签: javascript json

  1. 我不想使用jQuery。
  2. 如果可能,我想保留<mytag>
  3. 我有这种类型的json:

    {
        "datas": [
            {
                "id": "hotel_name",
                "value": "My hotel name"
            },
            {
                "id": "hotel_description",
                "value": "My description"
            }
        ]
    }
    

    从这个json,我想设置以下html标签的内容:

    <mytag id="hotel_name"></mytag>
    <mytag id="hotel_description"></mytag>
    

    要:

    <mytag id="hotel_name">My hotel name</mytag>
    <mytag id="hotel_description">My description</mytag>
    

    我已经尝试过了:

    function createElements(elements) {
        elements.datas.forEach(function (element) {
            var div = document.getElementById(element.id);
            div.innerHTML = element.value;
        });
    }
    
    var request = new XMLHttpRequest();    
    request.onload = createElements;
    request.responseType = "json";
    request.open("GET", "datas.json", true);
    request.send();
    

2 个答案:

答案 0 :(得分:0)

有一些问题:

  1. 响应未传递给onload()。必须从request.responseText

  2. 检索回复
  3. 您必须先使用JSON.parse()将JSON响应解析为对象,然后才能实际使用它。

  4. 注释掉request.responseType = "json";行。这似乎给出了神秘的InvalidStateError: DOM Exception 11错误。

  5. 你想这样做:

    function createElements(elements) {
        elements.datas.forEach(function (element) {
            var div = document.getElementById(element.id);
            // NOTE: Make sure `div` is not null so that an error is not raised when
            // an unexpected element is encountered.
            if (div != null) {
                div.innerHTML = element.value;
            }
        });
    }
    
    var request = new XMLHttpRequest();    
    request.onload = function() {
        var elements = JSON.parse(this.responseText); // Parse response.
        createElements(elements);
    }
    //request.responseType = "json"; // <-- Delete this line.
    request.open("GET", "datas.json", true);
    request.send();
    

答案 1 :(得分:0)

这是另一个答案:

<!DOCTYPE html>
<html>
<head>
    <title>your title</title>
</head>
<body>

<mytag id="hotel_name"></mytag>
<mytag id="hotel_description"></mytag>


<script type="text/javascript">
window.onload  = function (){   
   var json = {"datas": [{"id": "hotel_name", "value": "My hotel name"},
                         {"id": "hotel_description", "value": "My description"}
                        ]
              };

    var id="";
    var value = "";


    for(var i=0;i<json.datas.length;i++){

        id = json.datas[i].id;
        value = json.datas[i].value;
        document.getElementById(id).innerHTML = value;
    }

}
</script>
</body>
</html>

顺便说一下,为什么你要使用&#34; mytag&#34;,如果你使用&#34; mytag&#34;您的文档不再是有效的HTML文档

尝试在html validator

中验证此html文档

在底部你会得到这个: enter image description here

所以最好使用定义的html标签,如div,span,section等来获取有效的html文档