[英]ajax get empty array from json_encode()
So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
我使用 phphandler 文件從 ajax 調用 function:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
最后是 AJAX 電話
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
問題是 js 一直在控制台中顯示空數組。
json_encode 工作正常,因為 json_last_error = 0。
我嘗試將我的 getUsers() function 的返回替換為
echo json_encode($result);
測試 function 是否設法對我的數組進行編碼,它確實在頁面上顯示為 JSON 所以這不是我的數組問題的編碼。 當 AJAX 得到 json_encode function 的結果時,它仍然顯示一個空數組。
謝謝你的幫助 !
死靈。
解決方案 1您必須在回顯之前在 php 文件中設置 header 的內容類型
header('Content-type: application/json');
解決方案 2將 ajax 代碼中的dataType
更改為html
或將其刪除以返回默認dataType (default: Intelligent Guess (xml, json, script, or html))
然后使用 javascript JSON.parse()方法將返回的字符串轉換為 json。
我做了
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
header('Content-type: application/json');
echo json_encode($module -> getUsers());
?>
在我的 backendHandler 但整個頁面不再被解釋為 html 並且它只顯示源代碼。
我嘗試刪除數據類型。
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
success: function(response) { console.log(response); }
});
});
});
控制台仍然記錄一個空數組,所以我想它被檢測為 JSON。 我嘗試將其設置為 HTML 以查看 output 但即使在那里它仍然是 output 作為數組。 下面是控制台 output:
3 后端.php?module=users:19 []
感謝幫助
我試過這個,看看問題是否出在 function 中:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
echo json_encode($result);
return $result;
}
有了這個,我得到了我所期望的:一個代表 JSON 的大字符串,其中包含用戶信息。
然后我嘗試復制這個大字符串並將其傳遞給 json_encoder 並且它工作得很好。
但是當我使用我的 getUser function 的返回直接進入 json_encode 我得到空數組......
似乎 json_encoder 工作正常,但 AJAX 不斷得到一個空數組。
原來你的問題根本不是 json_encode,這是我的 static DB class 的問題,我在 AJAX 調用中被包含兩次。
無論如何感謝您的支持
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.