Javascript 无法通过php从服务器接收json
我无法在服务器上从php获取json javascript代码是:Javascript 无法通过php从服务器接收json,javascript,php,json,ajax,post,Javascript,Php,Json,Ajax,Post,我无法在服务器上从php获取json javascript代码是: $.ajax({ type: "POST", url: "doingSQL.php", data: label, success: function(result) { $("#p").html("All my book: <br>"+ result);
$.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");
}
});
但我在html控制台中得到的结果是“[]”或数组[0]
json是有效的json格式,如下所示:
{
"mybook":[
{
"book0":{
"id":"0",
"bookName":"bookA"
}
},
{
"book1":{
"id":"1",
"bookName":"bookB"
}
}
]
}
/* 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
但是,如果代码在php中的SQL连接之外。json返回将成功。
它看起来像:
{
"mybook":[
{
"book0":{
"id":"0",
"bookName":"bookA"
}
},
{
"book1":{
"id":"1",
"bookName":"bookB"
}
}
]
}
/* 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: {label:label}
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");
}
});
data: {label: label},
$.ajax({
类型:“POST”,
url:“doingSQL.php”,
数据:{label:label},
成功:功能(结果){
$(“#p”).html(“我的全部书籍:
”+结果);
控制台日志(结果);
},
数据类型:“json”,
错误:函数(xhr){
控制台日志(“错误”);
}
});
您需要在变量中传递标签
值。现在,由于您在PHP页面上使用的是$\u POST['label']
,因此请按如下方式传递变量:
$.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");
}
});
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");
}
});
$.ajax({
类型:“POST”,
url:“doingSQL.php”,
数据:{label:label},//在此处更改
成功:功能(结果){
$(“#p”).html(“我的全部书籍:
”+结果);
控制台日志(结果);
},
数据类型:“json”,
错误:函数(xhr){
控制台日志(“错误”);
}
});
关闭连接后,您似乎正在分配查询返回的值。还要注意,如果这是生产代码,您很容易理解为什么my php在编辑数据之前仍然可以获取标签值:{label:label}?例如,我可以使用标签值在php中进行sql选择,但不能返回JavaScript。