我无法从服务器上的php获取json
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控制台中得到的结果是&#34; []&#34;或数组[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
任何想法?
答案 0 :(得分:0)
只需将您的ajax data
传递给:
data: {label:label}
答案 1 :(得分:0)
data
的 ajax settings
属性可以是PlainObject
或String
或Array
的类型。有关详细信息,请参阅此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");
}
});
答案 2 :(得分:0)
您需要在变量中传递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");
}
});