在JavaScript中从PHP对象中提取mySQL查询结果
I apologize if this question has been asked before, but I can't seem to get on of them to work for me. The PHP script passes database results to JavaScript like this:
$queryResult = mysqli_query($dbase, $query);
if ($queryResult) {
$result = array();
while($row = mysqli_fetch_array($queryResult)) {
$result[] = $row;
}
}
echo json_encode($result);
JavaScript then receives this through AJAX (result of console.log):
[{"id":"1","name":"Babe Ruth","loginID":"babe","loginPW":"babe123"}]
I've tried JSON.stringify, Object.keys(arr), foreach ($arr as $key => $value), for(i in arr), but all to no success.
How can I read this as key-value pairs?
TIA.
如果以前曾问过这个问题,我道歉,但我似乎无法继续为他们工作 我。 PHP脚本将数据库结果传递给JavaScript,如下所示: p>
$ queryResult = mysqli_query($ dbase,$ query);
if($ queryResult){
$ result = array();
while($ row = mysqli_fetch_array($ queryResult)){
$ result [] = $ row;
}
}
echo json_encode($ result);
code > pre>
JavaScript然后通过AJAX (console.log的结果)接收到它 em>: p>
[{“ id“:”1“,”name“:”Babe Ruth“,”loginID“:”babe“,”loginPW“:”babe123“}]
code> pre>
我已经尝试了 JSON.stringify em>, Object.keys(arr) em>, foreach($ arr as $ key => $ value) em>, for(i in arr) em>,但都没有成功。 p>
如何将其作为键值对读取? p>
TIA。 p>
div>
You response is array of objects, You can use next code:
var users = JSON.parse(response);
for(var objId in users) {
// here you can use construction users[objId].your_key
console.log('id', users[objId].id);
console.log('name', users[objId].name);
console.log('loginID', users[objId].loginID);
console.log('loginPW', users[objId].loginPW);
}
I think you're looking for JSON.parse
, e.g
var user = JSON.parse(response)[0];
// Should print "Babe Ruth"
console.log(user.name);
What you've copied looks like a JS array containing one object.
Assuming your array is arr
then:
var obj = arr[0];
console.log(obj.id);
If what you pasted was actually a string, then you'll need to parse that JSON string with var arr = JSON.parse(response);
and continue as mentioned above.
You should get the index 0
of your response, then you can manipulate your object.
var response = [{"id":"1","name":"Babe Ruth","loginID":"babe","loginPW":"babe123"}];
response = response[0];
console.log(response.id);