簡體   English   中英

無法使用ajax解析響應

[英]Unable to parse response using ajax

所以我有一個js文件,該文件使用$.ajax發布JSON對象,然后我的php腳本接收該JSON對象並對其進行填充,但是,我無法從php腳本中獲得JSON響應(成功回調函數永遠不會運行)。

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對象的方式不正確的感覺。 任何幫助將非常感激。

你不應該

echo

使用Ajax dataType : json時,除json_encode之外的所有內容dataType : json您擁有的dataType : json

echo "Registered \\n";

之前

echo json_encode

刪除它,它應該工作

編輯:

當您在ajax調用中設置dataType : "json"時,則在調用完成后,響應應該在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);
}

希望它能消除您的困惑。

請刪除echo "Registered \\n"; echo "Register";時代碼中的行echo "Register"; Ajax請求將此返回到瀏覽器,並且您的實際數據echo json_encode($data); 永遠不要返回瀏覽器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM