简体   繁体   中英

JSON encoded data from PHP, doesn't display right when callback from jQuery

My HTML/jQuery Code

<div id="divResult"></div>

function doSearch(str){
var jsonString = str;//$.parseJSON//JSON.stringify(str);
$.ajax({
    type:'GET',
    url:'search.php',
    data:{data:jsonString},
    success:function(data){
        for( var key in data ) {
      alert(key);
    }       
});
}

My problem is that when I tried to parse the JSON (display it) I'm not getting the expected result, The data gets displyed in a manner of per text per line eg.

The JSON data was [{"userid:1,name:paul"},{"userid:5,name:jackson"}]

The display on the browser is like this,

[
{
"
u
s
e
r
i
d
:
1

and so on so forth...

I can't understand? is there something wrong?

I tried my js code with jsFiddle and it looks good,

I expect something like these;

1 Paul
5 Jackson

PHP Code is;

if ($stmt->execute(array("%$_GET[data]%"))) {
  while ($row = $stmt->fetch()) {    
    $aResult[] = array(
        'userid'    => $row['ui_userid'],
        'category'  => $row['ui_jocategory']
        );
        //print_r($aResult);
  }  
  echo json_encode($aResult);
}

Thanks in advance..

dataType: 'json'添加到您的ajax选项中。

The better solution might be to add a

header('Content-Type: application/json');

at the PHP side, specifying the data type of the response. This way jQuery will automatically know to parse the response into an object without need to specify dataType: "json" from the client side.

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