开发者

how to convert object to JSON

My jquery looks like this

var formContent ="action=view&msgid="+i开发者_StackOverflow中文版d;
$.getJSON("myserv.php",formContent, function(json){
    $.each( json, function(k, v){`
       alert( "Key: " + k + ", Value: " + v );`
    });
});

in my php file i have an array that i json encode

while($message->fetch()) {
    $arr[$i]["read"]=$message->test;
    $arr[$i]["messageid"]=$message2->test2;
    $arr[$i]["subject"]=$message2->test3;
    $arr[$i]["text"]=$message2->test4;
}

$str=json_encode($arr);

return $str;

the alert returns Key:0 Value: [Object Object]

Any idea how I can get it to return the correct result? How can I display the results nicely in a div or span?


You are putting it all in a single cell array. And then in your callback, in jQuery, you are trying to loop through the array cell. I'm assuming you want to keep $arr an array (guessing you could have multiple 'read', 'subject', etc) so you should change your js to:

var formContent ="action=view&msgid="+id;
$.getJSON("myserv.php",formContent, function(json){
    $.each(json, function(i){
        $.each(json[i], function(k, v) {
            alert( "Key: " + k + ", Value: " + v ); });
        });
    });
});

Or, if you don't want a single cell array, and will only return one 'read', 'subject etc, then change your PHP to:

if($message->fetch()) {
    $arr["read"]=$message->test;
    $arr["messageid"]=$message2->test2;
    $arr["subject"]=$message2->test3;
    $arr["text"]=$message2->test4;
    $str=json_encode($arr);
}
else {
    $str=json_encode(Array('error' => 'No message'));
}


return $str;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜