1

在这种情况下,我有一种读取或获取密钥名称的方法(如果我的术语是正确的),我指的是“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"
    }
}

]

4

2 回答 2

3

您可以使用点符号如果您的 json 响应看起来像

data = [{ key : value }, { key2 : value2} ]

您可以将键下的值设置为

var value = data[0].key;
var value2 = data[1].key;

编辑

好的,我在这里做了一个粗略的小提琴它将遍历您的 json 响应并将“homedata”或“faq”键的名称写入 div。请注意,它每次都会覆盖,因此 json 数组中的最后一个键将显示在最后。这只是为了说明如何获取键名。希望这会有所帮助

于 2012-11-13T08:41:05.740 回答
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
        }
    });

},

"

于 2012-11-13T08:49:03.063 回答