我正在尝试在从 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。
最佳答案
在你的 Ajax 中
编辑:
改变
datatype:"json",
不遵守参数名的大小写,t必须是T
dataType:"json",
请现在重试
$.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
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
在 PHP 中
就是这样,不要忘记退出;避免在您的 json 响应中包含 html 页面! 这是 }".. 之后的代码,它破坏了你的 json 输出 并使其无法被 javascript 读取(更糟糕的是,它只会破坏你的 javascript!)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
关于javascript - 提取 Json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34406735/