简体   繁体   中英

Failed to get value from Json_encode in jquery

I have a file whichh is converting my php array to 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);    
?>

and the jquery code to load the value

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

    }

});

But i am getting undefined in firebug console But i want the JSON value in jQuery variable.

Try setting the response content type to json

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

Assuming that you ensured that your server is echoing json data and not just an empty array,

Try

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM