【发布时间】:2023-08-17 16:23:01
【问题描述】:
我正在尝试提取从 php 文件发送的 jquery 中的 Json 响应。 这是 .js 代码:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
这是来自 php 文件的响应:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
我已经尝试了两个文件中我能想到的所有组合,但似乎没有任何效果。这是对数据库中用户名的简单检查。如果我控制台记录从响应中获得的数据,我会得到:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
所以信息在那里,但我如何访问它?我尝试了几种在互联网上找到的语法,但到目前为止还没有运气。我似乎记得json响应只能包含有效的json,那么问题是html吗?由于我的应用程序的结构,我认为我无法避免这种情况,因此希望可以使用我目前的结构访问 json。
【问题讨论】:
-
你是在 echo 之前发送 header("Content-Type: application/json"); 吗?
-
@user2182349 为什么这很重要?他在 AJAX 调用中有
dataType: "json",所以它会忽略内容类型。 -
@MaDaHoPe: 回答 ;) 不要忘记退出();避免在 json 响应中包含 html 页面!
-
@Barmar - 设置 Content-Type 以反映所服务的内容是一种很好的做法。
-
@user2182349 也许吧,但如果你在客户端显式编码它不会有什么不同。
标签: javascript php jquery json ajax