简体   繁体   English

JSON.parse(hr.response)错误

[英]JSON.parse(hr.response) error

I am trying to retrieve data from JSON. 我正在尝试从JSON检索数据。 I have written this code. 我已经写了这段代码。 It alerts "1" but doesn't alert "2". 它警告“ 1”,但不警告“ 2”。

<script type="text/javascript" src="jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
    function ajax_get() {
        var results = document.getElementByI("results");
        var hr = new XMLHttpRequest();
        hr.open("GET", "mylist.json", true);
        hr.responseType = "JSON";
        hr.setRequestHeader("Content-type", "application/json",true);
        hr.onreadystatechange = function() {
            if (hr.readyState == 4 && hr.status == 200) {
                alert('1');
                var data = JSON.parse(hr.response);
                alert('2');
                alert(data);
                results.innerHTML = data.name;
            }
        }
        hr.send(null);
        results.innerHTML = "request ...";
    }
</script>
</head>
<body>
    <div id="results"></div>
    <script type="text/javascript">ajax_get();</script>
</body>

You have already set the response type as json on this line. 您已经在此行将响应类型设置为json。

hr.responseType= "JSON";

So you need not parse the response again. 因此,您无需再次解析响应。 it will be by default json. 默认情况下它将是json。 Make sure your response is in json format and change your code like this. 确保您的响应是json格式,并像这样更改代码。

 var data  = hr.response;

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

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