无法使用ajax解析响应

时间:2017-11-21 21:33:20

标签: javascript php jquery json ajax

所以我有一个使用JSON发布$.ajax对象的js文件,然后我的php脚本获取该JSON对象并对其进行处理,但是,我无法获得json响应从PHP脚本返回(成功回调函数永远不会运行)。

register_script.js:

$.ajax({
    method: "post",
    dataType: "json",
    url: "http://localhost/login/webservices/register2.php",
    data: {
        reg_username: username,
        email: email,
        reg_password: password,
        confirm_password: confirm_pass
    },
    success: function (data) {
        alert("hello?");
        //alert(data.status);           

    }
}).fail(function (jqXHR, textStatus, errorThrown) {
    console.log("Post error: " + errorThrown);
});

register2.php:

if (isset($_POST['reg_username'], $_POST['email'], $_POST['reg_password'], $_POST['confirm_password'])) {
    $username = $_POST['reg_username']; //$_POST['from html']
    $email = $_POST['email'];
    $password = hash('md5', ($_POST['reg_password']));
    $confirm_password2 = hash('md5', ($_POST['confirm_password']));

    $sql = "INSERT INTO users (username, email, password) VALUES ('$username','$email','$password')";

    if ($password == $confirm_password2) {
        $response = sqlsrv_query($conn, $sql);
        if ($response) {
            $data = array(
                "username" => $username,
                "email" => $email,
                "password" => $password,
                "confirmPass" => $confirm_password2,
                "status" => "Registered",
            );
            echo "Registered \n";

        }
    }
}
//...
//some other validations
//...

echo json_encode($data);

我感觉我处理json对象的方式不正确。任何帮助将非常感激。

2 个答案:

答案 0 :(得分:0)

你不应该

echo

使用ajax json_encode

时,

dataType : json以外的任何内容

echo "Registered \n";

之前

echo json_encode

删除它,它应该工作

编辑:

当您在dataType : "json"电话中设置ajax时,预计在电话结束时,响应将在json,并且json以外的任何文字都会被编码响应中的字符串将导致错误。如果您仍需要调试并查看脚本采用的路径,可以在$data 中添加另一个索引(我假设$ data是一个数组) ,所以它就像

if($registered){
   $data['debug_logs'] .='Registration successfull----';
}

if($emailSent){
    $data['debug_logs'].='Email sent for registration-----';
}

echo json_encode($data);

然后在你的ajax成功函数中你可以像

一样使用它
success:function(data){
console.log(data.debug_logs);
}

希望它能解决你的困惑。

答案 1 :(得分:0)

当您将echo "Registered \n"; Ajax请求返回给浏览器时,请从代码中删除echo "Register";行,并且您的实际数据echo json_encode($data);永远不会返回浏览器。

相关问题