收到JSON我無法從PHP獲得JSON在服務器無法從服務器通過PHP
的JavaScript代碼:
$.ajax({
type: "POST",
url: "doingSQL.php",
data: label,
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
doingSQL.php的作業從SQL數據庫中選擇BOOKNAME和將數據轉換爲json。它看起來像這樣:
/* the server connecting code is omitted */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$label = $_POST["label"];
}
$sql = "SELECT * FROM book WHERE ower = '". $label."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Arr = array("id" => $row["book_id"],
"bookName" => $row["bookName"]);
$bookDetail[] = array("book".$i => $Arr);
}}
}
mysqli_close($conn);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json
但我在html控制檯得到的結果是「[]」或數組[0]。
的JSON是有效的JSON格式,它看起來像:
{
"mybook":[
{
"book0":{
"id":"0",
"bookName":"bookA"
}
},
{
"book1":{
"id":"1",
"bookName":"bookB"
}
}
]
}
然而,如果代碼是外在PHP SQL連接。 json返回將成功。 它看起來像:
/* the server connecting code is omitted */
mysqli_close($conn);
// if outside the SQL connection
$ArrA = array("id" => "0", "bookName" => "bookA");
$ArrB = array("id" => "1", "bookName" => "bookB");
$bookDetail[] = array("book0" => $ArrA);
$bookDetail[] = array("book0" => $ArrB);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json success
任何想法?
它看起來就像你分配從返回的值您關閉連接後的查詢。 –
另請注意,如果這是生產代碼,您很容易受到[SQL注入](https://en.wikipedia.org/wiki/SQL_injection) – Tserkov