提取Json响应

MaD*_*oPe 5 javascript php ajax jquery json

我试图从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');
 }
});
Run Code Online (Sandbox Code Playgroud)

这是来自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"}';
    }
Run Code Online (Sandbox Code Playgroud)

我已经尝试了两种文件中我能想到的所有组合,但似乎没有任何效果.它是对数据库中用户名的简单检查.如果我通过控制台记录我从响应中获得的数据,我得到这个:

    {"username":"available"}<!DOCTYPE html>
    // The rest of the page html
Run Code Online (Sandbox Code Playgroud)

所以信息在那里,但我如何访问它?我在互联网上尝试了几种语法,但到目前为止还没有运气.我似乎记得一个json响应只能包含有效的json,那么问题是html吗?由于我的应用程序的结构,我不认为我可以避免这种情况,因此希望可以使用我目前的结构访问json.

MTr*_*roy 2

在你阿贾克斯

编辑:

改变

datatype:"json",
Run Code Online (Sandbox Code Playgroud)

不考虑参数名称的大小写,t 必须是 T

dataType:"json",
Run Code Online (Sandbox Code Playgroud)

现在请重试

$.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');
    }
});
Run Code Online (Sandbox Code Playgroud)

在 PHP 中

就是这样,并且不要忘记退出;避免在 json 响应中包含 html 页面!这是 }".... 之后的代码,它破坏了您的 json 输出并使其无法被 javascript 读取(最糟糕的是,它只会破坏您的 javascript!)

echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
Run Code Online (Sandbox Code Playgroud)