无法从jquery中的Json_encode获取值

时间:2015-08-23 14:10:32

标签: php jquery json

我有一个文件,它将我的php数组转换为json

<?php
    include('lib/db.php');
    $cid = mysql_real_escape_string($_POST['id']);
    $q = rand(1, 2);
    $var = array();
    $rs1 = mysql_query("select * from questions where qid='$q' and sub_id='$cid'");
    while ($r1 = mysql_fetch_array($rs1)) {
        $var[] = array('qid' = > $r1['qid'], 'question' = > $r1['question'], 'ans' = > $r1['ans1'], 'ans2' = > $r1['ans2'], 'ans3' = > $r1['ans3'], 'ans4' = > $r1['ans4']);

    }
    print json_encode($var);    
?>

和加载值的jquery代码

$.ajax({
    url: "getquestion.php",
    type: "POST",
    data: "id=" + id,
    cache: false,
    dataType: "json",
    success: function (data, jqXHR) {

        if (data == null) {
            alert('nothing');

        } else {
            alert(data[0]);
        }

    }

});

但我在firebug控制台中得到了未定义但是我想在jQuery变量中使用JSON值。

2 个答案:

答案 0 :(得分:0)

尝试将响应内容类型设置为json

header('Content-type: application/json');
print json_encode($var);

答案 1 :(得分:0)

假设您确保服务器正在回显json数据而不仅仅是一个空数组

尝试

success: function (data) {
    // console.log(data);
    var buffer = "";
    for(var i=0;i<data.length;i++) {
           buffer += "Question ID:" + data[i].qid + "Question: " + data[i].question + "<br>";
           ....
        }
        $("#container").html(buffer); //display the retrieved content on the webpage
    }