用json中的值填充元素 [英] Fill element with value in a json

查看:104
本文介绍了用json中的值填充元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这种类型的json:

I have this type of json:

{
    "datas": [
        {
            "id": "fruit_name",
            "value": "Banana"
        },
        {
            "id": "fruit_description",
            "value": "This is a banana."
        },
        ...

如何使用其值自动完成以下html?

How can I autocomplete the following html with their value ?

<div id="fruit_name"></div>
<div id="fruit_description"></div>

我已经尝试过:

function createElements() {
    // Parse JSON response.
    var elements = JSON.parse(request.responseText);

    elements.datas.forEach(function (element) {
        var div = document.getElementById(element.id);
        div.innerHTML = element.value;
    });
}

var request = new XMLHttpRequest();    
request.onreadystatechange = function() {
    if (request.readyState === 4) {
        createElements();
    }
}
request.responseType = "json";
request.open("GET", "datas.json", true);
request.send();

但是它不起作用,并且出现此错误:

But it does not work and I have this error:

[Error] InvalidStateError: DOM Exception 11: An attempt was made to use an object that is not, or is no longer, usable.
    createElements (index.html, line 20)
    onreadystatechange (index.html, line 31)

有人帮助我吗?

谢谢.

推荐答案

request可能未在函数中(在范围内)定义.您可以调用它并使用this或以下

request is probably not defined (in scope) in your function. Either you can call it and use this or of the following

function createElements(request) {//Get the 'request' passed.
    // Parse JSON response.
    var elements = JSON.parse(request.responseText);

    elements.datas.forEach(function (element) {
        var div = document.getElementById(element.id);
        div.innerHTML = element.value;
    });
}

var request = new XMLHttpRequest();    
request.onreadystatechange = function() {
    if (request.readyState === 4) {
        createElements(request);//Pass in 'request'
    }
}

request.responseType = "application/json";//Remove line if there are errors
request.open("GET", "datas.json", true);
request.send();

这篇关于用json中的值填充元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆