![](/img/trans.png)
[英]Json_encode many data in PHP from database to Jquery AJAX
[英]how to read JSON data from PHP json_encode using Jquery AJAX
在這里呆了幾天。 使用jquery ajax執行某些操作並嘗試從我的服務器獲取json編碼的響應。 不知道為什么現在對我有用。
以下是我的Javascript函數
function checkFriendsEmail(friendsEmail){
var request = $.ajax({
url : 'http://localhost/loginsentology/serverside/checkfriendexist2.php',
type: 'POST',
data: {
'checkfriend' : 'checkfriend',
'friendsemail' : friendsEmail,
},
success: function(data) {
console.log(data); <<<-- Comes back to my console as a JSON obj
console.log(data.nouser); <<-- Comes back undefined
}
我在控制台中得到了這個結果。 {“ nouser”:[“ noUserExist”]} <<< -----我該怎么抓。
我的PHP低於
$fdarray = array();
$_db = DB::getInstance();
$_query = $_db->query('SELECT * FROM users WHERE email = ? ', array($_POST['friendsemail']));
$results = $_query->results();
$numberOfRows = $_db->numberOfRows();
if ($numberOfRows == 0) {
//$noUserExist = 'NoUserExist';
$fdarray['nouser'] = array();
array_push($fdarray['nouser'], 'noUserExist');
echo json_encode($fdarray);
return false;
}
else {
//friends email exist in users db --> now we must check to see if friend has devices
$friendsEmail = $results[0]->email;
if ($_POST['friendsemail'] == $friendsEmail) {
$id = $results[0]->id;
$_db2 = DB::getInstance();
$_query2 = $_db2->query('SELECT * FROM devices WHERE userid = ? ', array($id));
$results2 = $_query2->results();
$numberOfRows2 = $_db2->numberOfRows();
if ($numberOfRows2 == 0) {
//user has no devices attached to name
$fdarray['userexist'] = array();
$fdarray['nodevices'] = array();
array_push($fdarray['userexist'], true);
array_push($fdarray['nodevices'], 'noDevicesForUser');
echo json_encode($fdarray);
return false;
}
else {
$fdarray['userexist'] = array();
$fdarray['devices'] = array();
array_push($fdarray['userexist'], true);
for ($i = 0; $i < $numberOfRows2; $i++) {
array_push($fdarray['devices'], $results2[$i]->devicename);
}
//end for statement
}
//end number of rows2
echo json_encode($fdarray);
}
//end firendsemail == firendsemail
}
我只是想通了。 我在json_encode
之前是print_r($_POST)
。
您需要指定將JSON對象發送回瀏覽器,然后才能在PHP代碼中將其回顯。
header("Content-type: application/json");
在您的ajax函數中,您還想指定dataType為json
var request = $.ajax({
url : 'http://localhost/loginsentology/serverside/checkfriendexist2.php',
type: 'POST',
data: {
'checkfriend' : 'checkfriend',
'friendsemail' : friendsEmail,
},
success: function(data) {
console.log(data); //<<<-- Comes back to my console as a JSON obj
console.log(data.nouser); //<<-- Comes back undefined
console.log(data.nouser[0]);
},
dataType: 'json'
});
根據返回的結果來判斷{ "nouser" : ["noUserExist"] }
-注意方括號-所需的值存儲在數組中,因此您需要:
console.log(data.nouser[0]);
如果console.log(data.nouser);
聲明正在返回
{ "nouser" : ["noUserExist"] }
那你可以試試
console.log(data.nouser[0]);
應該返回noUserExist
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.