Javascript xhr.responseText是';t通过JSON.parse()转换为对象
我编写此函数是为了向以字符串格式提供JSON对象的服务器发出ajax请求。我想使用Javascript xhr.responseText是';t通过JSON.parse()转换为对象,javascript,json,ajax,Javascript,Json,Ajax,我编写此函数是为了向以字符串格式提供JSON对象的服务器发出ajax请求。我想使用JSON.parse()将这些JSON对象解析为Javascript对象。但是当我检查JSON.parse()返回的对象类型时,它是一个字符串!下面是函数: function getDBMatches(){ var xhr = createXHR(); xhr.dropdown = this.parentNode.parentNode.getElementsByClassName("dropdow
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);
}
函数getDBMatches(){
var xhr=createXHR();
xhr.dropdown=this.parentNode.parentNode.getElementsByClassName(“下拉内容”)[0];
xhr.dropdown.innerHTML=“”;
如果(!xhr.dropdown.classList.contains('show')){
xhr.dropdown.classList.add('show');
}
xhr.onreadystatechange=函数(){
如果(this.value==“”){
返回;
}
if(xhr.readyState==4){
如果((xhr.status>=200&&xhr.status<300)| | xhr.status==304){
var xhrResponse=xhr.responseText;
警报(xhrResponse);/“[{\“model\”:\“workoutcal.liftactivity\”,“pk\”:1,\“fields\”:{\“name\”:“benchpress\”}]
警报(xhrResponse的类型);//字符串
var dbMatches=JSON.parse(xhrResponse);
alert(typeof dbMatches);//字符串!这是我不明白的。
对于(var i=0;iJSON.parse()
返回文本,根据传递给解析函数的参数,文本可以是object、string或其他类型。考虑下面的表达式,它将返回类型字符串<代码> Val< /Cord>。
var val = JSON.parse(JSON.stringify("Hello"));
console.log(xhrResponse)
JSON.parse完全可能返回一个字符串:当您将字符串编码为JSON:console.log(JSON.parse('foo'))时,console.log(xhrResponse)
的输出是什么
@Sandi:这证实了我刚才说的话。您将字符串编码为JSON。外部“…”
是从服务器发送的响应的一部分,使其成为JSON中的字符串。如果它是一个对象数组,那么响应将是[{“model”:…}]
。当然可以。如果你编码两次,你必须解码两次。但更好的解决方案是不编码两次。