我正在使用ajax(jquery)查询我的数据库,但我收回的数据证明很难处理。我注意到其他人发布了类似的问题,并确定了PHP代码(特别是如何将数据分配给数组)作为问题。但是我找不到解决方案。我返回的数据的内容(当我将返回的数据转换为字符串时)如下所示:
<?php
$replace = array('{COVER_AMT}','{LIABILITY_AMT}','{TOTAL_AMT}', 'This is total amount : 0');
$with = array('90', '90', '0','');
$myString = 'This is Cover Amt : {COVER_AMT} . This is liablity amount : {LIABILITY_AMT} . This is total amount : {TOTAL_AMT}';
echo str_replace($replace, $with, $myString);
?>
我真的希望能够从返回的数据中提取单个元素,例如userLastLogin字段。
我的ajax查询:
<?php
$replace = array('{COVER_AMT}','{LIABILITY_AMT}','{TOTAL_AMT}');
$with = array('0', '90', '0');
$myString = 'This is Cover Amt : {COVER_AMT} . This is liablity amount : {LIABILITY_AMT} . This is total amount : {TOTAL_AMT}';
$myString = str_replace($replace, $with, $myString);
$myString_array = explode("This is",$myString);
foreach($myString_array as $myString_sliced) {
$pattern = '/(\.?)(This is )(.*?) 0(\s?)(\.?)/i';
$replacement = '';
if($myString_sliced)
echo preg_replace($pattern, $replacement, "This is ".$myString_sliced);
}
?>
我的PHP下面:
[{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin@admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}]
答案 0 :(得分:1)
您可以像这样(客户端)
访问数组中的各个元素$.ajax({
....
....
success: function (res) {
alert(res[0].userLastLogin);
// OR
alert(res[0]['userLastLogin']);
}
});
答案 1 :(得分:1)
这会帮助你
<强> JS 强>
success: function (res) {
var res = [{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin@admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}];
$.each(res,function(key,value){
alert(res[key].id);
alert(res[key].userName);
alert(res[key].userPassword);
alert(res[key].userEmail);
alert(res[key].userRegistrationIP);
alert(res[key].registrationDateTime);
alert(res[key].userLastLogin);
})
}
答案 2 :(得分:1)
看看这个:
$.ajax({
url: 'authenticate2.php',
type: 'POST',
success: function(res) {
var response = $.parseJSON(res);
console.log(res.userLastLogin);
})
或者你可以在你的ajax成功中做到这一点:
$.each(JSON.parse(res), function() {
console.log(this[Object.keys(this)[6]]);
});
答案 3 :(得分:0)
试试这个
var json = '{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin@admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}';
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.userLastLogin);
}
答案 4 :(得分:0)
如果您只想使用userLastLogin数据,那么你可以试试这个,
while($r = mysqli_fetch_assoc($result)) {
$rows['userLastLogin'] = $r['userLastLogin'];
}