JSON.parse(request.responseText)不会返回所有数据

时间:2017-08-23 04:52:51

标签: javascript json ajax xmlhttprequest

这是有问题的javascript部分。我正在使用JSON.parse,当我在控制台中记录它时,描述键/值没有显示。

var jsonOptions = JSON.parse(request2.responseText);
jsonGlobal = jsonOptions; 
console.log(request2.responseText);

我的json文件看起来像这样

[{"level": "1","number": "1","title": "blah blah blah","description": "aaaa"},
{"level": "1","number": "1.1","title": "blah again","description": "aaa" }]

这是完整的javascript

<script>
var dataList2 = document.getElementById('json-datalist');
var input2 = document.getElementById('ajax2');
var request2 = new XMLHttpRequest();
var jsonGlobal ;

request2.onreadystatechange = function (response) {

    if (request2.readyState === 4) {
        if (request2.status === 200) {
            // Parse the JSON
            var jsonOptions = JSON.parse(request2.responseText);
            jsonGlobal = jsonOptions; 
            console.log(request2.responseText);
            // console.log(jsonGlobal)
            // Loop over the JSON array.
            jsonOptions.forEach(function (item) {
                // Create a new <option> element.
                var option = document.createElement('option');
                // Set the value using the item in the JSON array.
                option.value = item.title;
                option.setAttribute('data-number', item.number);
                option.setAttribute('data-description',item.description); // add this line for description
                //<--
                // Add the <option> element to the <datalist>.
                dataList2.appendChild(option);
            });

            // Update the placeholder text.
            input2.placeholder = "Start Enterting a Title...";
        } else {
            // An error occured :(
            input2.placeholder = "Couldn't load datalist options :(";
        }
    }
};


// Update the placeholder text.
input2.placeholder = "Loading options...";

// Set up and make the request2.
request2.open('GET', '/static/json/all-titles.json', true);
request2.send();
</script>

这是控制台中显示的内容

[
 {
  "level": "1",
  "number": "1",
  "title": "blah blah blah"
 },

有关为什么描述部分没有出现的任何想法?

1 个答案:

答案 0 :(得分:0)

您的问题包含答案:

当您执行console.log(request2.responseText)时,您说您收到以下输出:

[
 {
  "level": "1",
  "number": "1",
  "title": "blah blah blah"
 },

此行与JSON解析无关。它只是打印出响应包含的内容。您的服务器未在响应中发送描述数据。