2015-08-23 142 views
1

我有whichh正在转换我的PHP阵列中的文件,以JSON无法从Json_encode获得价值jQuery中

<?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]); 
     } 

    } 

}); 

但我正在逐渐未定义在萤火虫控制台但我想在JQuery变量的JSON值。

回答

0

尝试将响应内容类型为JSON

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

做到这一点仍然没有得到任何东西 –

+0

检查萤火虫的网络面板,看看从你的服务器返回什么 – bumpy

+0

JSON没有返回 –

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 
    }