通过变量读取和解析JSON
我有一个存储为keyvalue的值。例如,在这种情况下,“12F”。我想看看它是否存在于我的JSON中。如果是这样,我想获取PNG值。如果没有,只是发送一条消息回通过变量读取和解析JSON
JSON
{
"Property": "99",
"12F": {
"png": "12-74"
},
"13F": {
"png": "12-74"
}
}
JQUERY
var sourceurl = '../floorplan-data.json';
var thekeyvalue = $("#finalkey").text();
//start ajax request
$.ajax({
url: sourceurl,
//force to handle it as text
dataType: "text",
error:
function(){
//error
},
success: function(data) {
var json = $.parseJSON(data);
console.log(json.thekeyvalue); //having trouble here
}
});
这是你成功的功能应该如何。请检查。
var sourceurl = '../floorplan-data.json';
var thekeyvalue = $("#finalkey").text();
//start ajax request
$.ajax({
url: sourceurl,
//force to handle it as text
dataType: "text",
error:
function(){
//error
},
success: function(data) {
var json = $.parseJSON(data);
if(json["12F"]])
return json["12F"].png;
else
return "";
}
});
似乎它不会解析“undefined”当它回来“undefined”时,我不断收回一个错误,说:未捕获TypeError:无法读取属性'png'的Object.success undefined – Omar
尝试catch成功函数为我工作,但我想知道是否有更好的方法:在这里找到:https://stackoverflow.com/questions/14782232/how-to-avoid-cannot-read-property-of-undefined-errors尝试{ window.abc } catch(e){0} { console.log(“YO”,e) } – Omar
您可以尝试使用'if(json [“12F”]])'if if条件来检查值是否为'undefined'。 –
你为什么使用'dataType:“text”'? – SLaks
试试'json [thekeyvalue]'。说明:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Property_Accessors – Will
omg严重这就是它,但是当它无法找到它时,它将“undefined”发送给成功功能而不是错误。如果不存在,我如何触发jquery。 – Omar