提取Json响应

Extract Json response

本文关键字:响应 Json 提取      更新时间:2023-09-26

我正在尝试提取从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;

当您响应AJAX调用时,应该只返回JSON响应,而不是页面的HTML。添加:

exit();

在这段代码之后,这样您就不会在JSON之后显示HTML了。

在JS代码中,使用if (data.username == 'available')来判断用户名是否可用。

你代码中的另一个问题是你在这里有一个拼写错误:

datatype: 'json',

它应该是dataType,并带有大写的T

你也可以放:

header("Content-type: application/json");

在回显脚本中的JSON之前,jQuery将自动解析响应。

您还可以在jQuery ajax调用beforeSend函数中设置请求头,如下所示

beforeSend: function (xhr) {
                xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
                xhr.setRequestHeader('Accept', 'application/json');
}

因此,您严格地将数据类型声明为json