我有办法阅读或获取密钥名称(如果我的用语是正确的)在这种情况下,我指的是“homedata”或“faq”。我想知道是否是“homedata或”faq“,以便我可以将它存储在变量中并用于比较。 对于我的jquery,这是我的脚本:
var varHolder ="";
$.ajax({
type: "POST",
//data: data_json,
dataType: "json",
url: "sql_queries.php",
success: function(data) {
$.each(data, function(key, val) {
//read the index name here and store it to varholder
varHolder = data[key];
//then compare it like this
if(varHolder == "homedata"){
//write something to the dome
}else if(varHolder == "faq"){
//write something to the dome
}
});
},
error:function(){
console.log("error fetching data. please refresh the page");//alert("Send Email Failure,Please try again");
},
complete:function(){
console.log("complete");//alert("Send Email Failure,Please try again");
}
});
这是我的json结果:
[
{
"homedata":
{
"approve_title":"home bla blah",
"approve_desc":"this is the approve JSON"
}
},
{
"homedata":
{
"approve_title":"another home bla blah",
"approve_desc":"tthis is the approve JSON",
"approve_path":"backend/pdf/this is the approve JSON.pdf"
}
},
{
"faq":
{
"progproj_title":"whatever JSON",
"progproj_details":"sos sos sos"
}
}
]
答案 0 :(得分:3)
您可以使用点符号 如果您的json响应看起来像
data = [{ key : value }, { key2 : value2} ]
您可以在键下获取值
var value = data[0].key;
var value2 = data[1].key;
修改强>
好的,我做了一个粗略的fiddle here它将遍历你的json响应,并将“homedata”或“faq”键的名称写入div。请注意,它将每次覆盖,因此json数组中的最后一个键将显示在最后。这只是为了说明如何获得关键名称。希望这有助于
答案 1 :(得分:0)
“的console.log(数据);” //这已经保留了索引的名称 所以你可以这样做 elementIndexName =''+ data; 要么 “ $ .each(data,function(key,val){
//read the index name here and store it to varholder
varHolder = ""+data;
//then compare it like this
if(varHolder == "homedata"){
//write something to the dome
}else if(varHolder == "faq"){
//write something to the dome
}
});
},
“