我将php的JSON结果分配给了一个javascript变量。 返回的结果如下所示,但它给了我未定义 未定义
[{"a":"2","u":"jamesoduro","l":"Oduro","f":"James"},{"a":"5","u":"deary.grace","l":"Grace","f":"Dear"}]
我简单地知道这看起来像一个带有两个对象的javascript数组。 我试图访问对象内的数据但无济于事。 下面是脚本:
PHP
<?php
//fetch online users
$array = array();
$sql = "SELECT id as a,username as u, lastname as l,firstname as f FROM users WHERE active =1 limit 2";
$q = mysqli_query($dbc_conn,$sql);
while($row = mysqli_fetch_assoc($q)){
$array[] = $row;
}
$json = json_encode($array);
echo $json;
?>
JQUERY
$(document).ready(function(){
//checking online users
setTimeout(function(){
$.ajax({
url:"testing.php",
type:"post",
success:function(response){
var array = response;
console.log(array[0].f +" "+ array[0].l);
}
});
},200);
});
请问可能是什么问题?谢谢
答案 0 :(得分:2)
@interface MainViewController () <ChildViewControllerDelegate>
@end
@implementation MainViewController
- (void)viewDidAppear:(BOOL)animated {
// creating frame for child and placing it on the bottom of the screen
CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
CGFloat yOffset = self.view.frame.origin.y;
CGFloat childHeight = (8/15) * screenWidth;
CGRect child = CGRectMake(0, screenHeight - yOffset - childHeight, screenWidth, childHeight);
// adding storyboard
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"child" bundle:nil];
ChildViewController *childVC = [storyboard instantiateViewControllerWithIdentifier:@"childViewController"];
childVC.view.frame = childBox;
[self addChildViewController: childVC];
[self.view addSubview:childVC.view];
}
- (void) closeChild {
NSLog(@"Why doesn't this get trigger???");
}
@end
你从php得到一个字符串,需要将字符串转换为json对象。
你必须学会调试你的代码,以找出我猜错的地方。
答案 1 :(得分:1)
尝试反序列化响应:
var array = JSON.parse(response);
<强>说明强>
您从ajax调用获得的响应类型为 string ,因此您必须将其转换为对象。这就是JSON.parse()方法的作用:它解析JSON字符串并创建此字符串表示的对象,遵循特定规则(解析后的字符串必须采用valid JSON格式< /强>)。
答案 2 :(得分:1)
保持服务器端PHP脚本代码干净整洁
例如
ob_clean();
echo json_encode($array);
在客户端,如果您在ajax中获得JSON响应,请在ajax选项中传递dataType:'json'
$.ajax({
url:"testing.php",
type:"post",
dataType:"json",
success:function(response){
console.log(response[0].f +" "+ response[0].l);
}
});