无法从服务器通过PHP
问题描述:
收到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
任何想法?
答
只是通过你的Ajax data
为:的PlainObject
或String
或Array
data: {label:label}
答
的ajax settings
的data
属性可以是类型。欲了解更多信息,请参阅此http://api.jquery.com/jquery.ajax。
所以你的JavaScript代码会是这样的:
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label},
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
+0
为什么我的php仍然可以在编辑数据之前获得标签值:{ label:label}?例如,我可以使用标签值在php中进行sql选择,但不能返回到JavaScript。 –
答
你需要在一个变量传递label
值。现在,因为PHP的页面上使用的是$_POST['label']
,所以传递变量是这样的:
data: {label: label},
所以你完全AJAX代码是这样:
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label}, // changed here
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
它看起来就像你分配从返回的值您关闭连接后的查询。 –
另请注意,如果这是生产代码,您很容易受到[SQL注入](https://en.wikipedia.org/wiki/SQL_injection) – Tserkov