如何将Ajax响应转换为字符串以与JS字符串进行比较

3

如何将Ajax响应转换为纯文本字符串?我有一个全局变量,并将ajax响应存储到其中,但是当我将其与JavaScript字符串进行比较时,即使它们相等,它也会返回false。

这是我的代码:

function checkUsn(){
    var usn = document.getElementById("usn").value;
    if(usn){
        $.ajax({
            type: 'post',
            url: 'checkdata.php',
            data: {
                emp_username: usn,
            },
            success: function(response){
                console.log(response);
                myGlobalContainer.usn = response; //convert it to compare with string
                $('#status').html(response);
            }
        });
    }
}

在控制台中,当我输入数据库中已存在的用户名时,它会记录OK。这个OK存储在myGlobalContainer.usn中,但是当我像下面的代码进行比较时,它返回false。

if(myGlobalContainer.usn == "OK"){
return true;
}else{
return false;
}

我将添加 PHP 文件。
<?php
header("Content-Type: text/plain");
include 'db_config.php';
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);

if(isset($_POST['emp_username'])){
    $usn = $_POST['emp_username'];

    $checkdata = "SELECT emp_username FROM emp_details where emp_username='$usn'";

    $query = mysqli_query($conn, $checkdata);

    if(mysqli_num_rows($query) > 0){
        echo "OK";
    }else{
        echo "Your Username not exist";
    }
    exit();
}

if(isset($_POST['emp_pw']) && isset($_POST['emp_usn'])){
    $pw = $_POST['emp_pw'];
    $usn = $_POST['emp_usn'];

    $get_pw = "SELECT emp_password FROM emp_details where emp_username='$usn'";

    $query = mysqli_query($conn, $get_pw);

    //$get_num_rows = mysqli_num_rows($query);
    //echo $get_num_rows;

    $row = mysqli_fetch_assoc($query);
    //echo $row["emp_password"];

    // check if password is match with username
    if($pw == $row["emp_password"]){
        echo "MATCH";
    }else{
        echo "Wrong password";
    }
    exit();
}
?>

Please help Thanks!


1
我认为问题不在于字符串比较,response 很可能已经是一个字符串了。问题可能是在你执行比较 myGlobalContainer.usn == "OK" 的代码之前,在 Ajax 回调中设置了值。回调函数是异步执行的。 - Patrick Hund
尝试使用JSON.stringify(response); - Habeeb
你的 if(myGlobalContainer.usn == "OK") 代码在什么时候/地方确切地执行? - Phil
3个回答

2
我已经修改了我的代码为:


    success: function(response){
        console.log(response);
        myGlobalContainer.usn = response.trim(); //convert it to compare with string
        $('#status').html(response);

它可以工作,但是伙计们,感谢你们的帮助非常感激!同时也感谢这个问题Ajax response doesn't equal what I think it should


你的PHP代码中可能有一些空白字符(换行符等),这些在你的问题中没有显示出来。 - Phil
Phil> 不是 - 我遇到了同样的问题,而且我的PHP代码是干净的 - 但是似乎在JavaScript中需要修剪一下。 - Razvan_TK9692

1
默认情况下,jQuery的ajax函数会根据Content-Type响应头确定所接收到的数据类型。 您可以使用dataType参数覆盖此设置。
$.ajax({
    dataType: "text",
    // etc etc
});

然而,由于响应似乎是“OK”,而不是HTML,因此很可能需要调整PHP以输出正确的Content-Type:

<?php
    header("Content-Type: text/plain"); # Override the default (text/html)
    echo "OK";

因此,还要确保响应只是简单的“OK”,而不是输出(例如)“OK”后跟一个换行符。


嗨Quentin先生,它不起作用,即使我在php文件中加入了header("Content-Type: text/plain");并在ajax中添加了dataType: "text"。 - Basch

0

我觉得你应该在ajax成功的回调函数中使用一个函数。

var myGlobalContainer.usn = "";
function signAndCompare(str)
{
     myGlobalContainer.usn = str
     if(myGlobalContainer.usn == "OK")
         {
             console.log("true");
             return true;
          }
     console.log("false");
     return false;
 }

function checkUsn(){
var usn = document.getElementById("usn").value;
if(usn){
    $.ajax({
        type: 'post',
        url: 'checkdata.php',
        data: {
            emp_username: usn,
        },
        success: function(response){
            console.log(response);
            signAndCompare(response);//this line: **compare** and sign response
            $('#status').html(response);
        }
    });
}

嗨,阿里雷扎先生,谢谢您的回复。我尝试了您的解决方案,但它不起作用。 - Basch
1
FYI,var myGlobalContainer.usn = "";是无效的。你想要的是 var myGlobalContainer = { usn: '' } 或者类似的语法。 - Phil

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接