Javascript 为什么我得到一个空洞的回答?
我正在尝试从表中获取所有列名:Javascript 为什么我得到一个空洞的回答?,javascript,php,jquery,json,Javascript,Php,Jquery,Json,我正在尝试从表中获取所有列名: $query = "SHOW columns FROM table;"; $json = array(); if ($result = $link->query($query)) { while($row = $result->fetch_assoc()){ array_push($json, $row['Field']); } } header( 'Content-Type: application/json' ); //
$query = "SHOW columns FROM table;";
$json = array();
if ($result = $link->query($query)) {
while($row = $result->fetch_assoc()){
array_push($json, $row['Field']);
}
}
header( 'Content-Type: application/json' );
//print_r($json);
echo json_encode($json);
exit;
jQuery代码:
$.ajax({
type: "POST",
dataType: "json",
data : {
q : "abc"
},
success : function(data) {
if(data.length!=0){
console.log(JSON.stringify(data));
$("#content").append(data);
}
else{
$("#content").text("no data");
}
},
error : function(data) {
console.error("error: " + data));
}
});
当我使用print\r($json)
时,我得到了这个响应,这是正确的:
"Array\n(\n [0] => ID\n [1] => Name\n [2] => Age\n [3] => Gender\n )\n"
但是当我使用json\u encode($json)
时,我得到的没有数据
,因此响应是空的
更新
好的,我取消了数据类型的注释:“json”
,添加了标题('Content-Type:application/json')
并按建议编辑错误回调
这是我收到的错误消息:
parsererror SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Stack-Trace:
m.parseJSON@http://code.jquery.com/jquery-latest.min.js:4:15732
Pc@http://code.jquery.com/jquery-latest.min.js:4:18120
x@http://code.jquery.com/jquery-latest.min.js:4:21525
.send/b@http://code.jquery.com/jquery-latest.min.js:4:25897
在回显结果之前,应设置正确的标题类型:
header( 'Content-Type: application/json' );
echo json_encode( $json);
另外,尝试将AJAX请求类型设置为GET
,而不是POST
:
$.ajax({
type:'GET',
data: 'q=abc',
success : function(data) {
if(data.length!=0){
console.log(JSON.stringify(data));
$("#content").append(data);
}else{
$("#content").text("no data");
}
},
error : function(data) {
console.error("error: " + data));
}
});
更新
如果您使用的是Google Chrome(强烈推荐),请使用Inspector(Ctrl+Shift+I)的网络选项卡,XHR子部分,您将在其中看到AJAX请求的尝试
在名称列下,单击请求,在右侧,您可以使用标题和响应部分检查AJAX请求是否正常。Put
console.log(数据)在success()
函数中编写>并查看其结果(在if语句之前)。取消对dataType:“json”
行的注释。另外,尝试正确使用error
回调:error:function(jqXHR,status,error){console.log(status,error);}
。好的,我已经相应地更新了它。