xhr.responseText未通过JSON.parse()转换为对象

时间:2018-01-02 11:23:36

标签: javascript json ajax

我编写了这个函数来向我的服务器发出ajax请求,这些请求以字符串格式提供JSON对象。我想使用JSON.parse()将这些JSON对象解析为Javascript对象。但是当我检查JSON.parse()返回的对象的类型时,它是一个字符串!这是功能:

function getDBMatches(){
    var xhr = createXHR();

    xhr.dropdown = this.parentNode.parentNode.getElementsByClassName("dropdown-content")[0];
    xhr.dropdown.innerHTML = "";
    if(!xhr.dropdown.classList.contains('show')){
        xhr.dropdown.classList.add('show');
    }

    xhr.onreadystatechange = function(){
        if (this.value == ""){
            return;
        }
        if (xhr.readyState == 4){
            if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){

                var xhrResponse = xhr.responseText;
                alert(xhrResponse); // "[{\"model\": \"workoutcal.liftactivity\", \"pk\": 1, \"fields\": {\"name\": \"benchpress\"}}]"
                alert(typeof xhrResponse); // string

                var dbMatches = JSON.parse(xhrResponse);
                alert(typeof dbMatches); // string! This is what I don't understand.

                for(var i = 0; i < dbMatches.length; i++){
                    var link = document.createElement("a");
                    link.innerHTML = dbMatches[i]["name"];
                    link.onclick = function(){
                        var textbox = link.parentNode.parentNode.getElementsByTagName('input')[0];
                        textbox.value = link.innerHTML;
                        xhr.dropdown.innerHTML = "";
                    };
                    xhr.dropdown.appendChild(link);
                }
            } else {
                document.getElementById("xhrPar").innerHTML = "Request was unsuccessful: "+xhr.status;
            }
        }
    };

    var url = "http://localhost:8000/workoutcal/";
    if (this.name == "lift_string"){
        url += "get_lifts";
    } else if (this.name == "cardio_string"){
        url += "get_cardio";
    }
    url = addURLParam(url, this.name, this.value);

    xhr.open("get", url, false);
    xhr.send(null);

}

为什么不将字符串解析为Javascript对象?

1 个答案:

答案 0 :(得分:0)

JSON.parse()返回literal,它可以是Object,String或其他类型,具体取决于传递给parse函数的参数。考虑下面的表达式,它将返回类型为string的val

var val = JSON.parse(JSON.stringify("Hello"));