简体   繁体   English

来自PHP的JSON编码数据,从jQuery回调时无法正确显示

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

My HTML/jQuery Code 我的HTML / jQuery代码

<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. 我的问题是,当我尝试解析JSON(显示它)时,没有得到预期的结果,例如,数据以每行每文本的方式显示。

The JSON data was [{"userid:1,name:paul"},{"userid:5,name:jackson"}] JSON数据为[{“ 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, 我用jsFiddle尝试了js代码,看起来不错,

I expect something like these; 我期望这样的事情;

1 Paul
5 Jackson

PHP Code is; PHP代码是;

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. 在PHP端, 指定响应的数据类型。 This way jQuery will automatically know to parse the response into an object without need to specify dataType: "json" from the client side. 这样,jQuery将自动知道将响应解析为一个对象,而无需从客户端指定dataType: "json"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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