doudi5892 2013-05-22 01:29
浏览 22
已采纳

jQuery无法比较AJAX返回的数据

I am trying to get a form to check if a surname already exists in the database.

It seems like it is working, it checks the database and returns values, eg the number, as a string, of times the surname exists, or 'none' if they did not enter a surname.

The problem I am having is when I try to display the results.

JavaScript:

sName = $('#sName'), sInfo = $("#sInfo");
sName.blur(function() {
        $.ajax({
            type: "POST",
            data: "sName="+$(this).attr("value"),
            url: "check.php",
            beforeSend: function(){
                sInfo.html("<font color='blue'>Checking Surname...</font>");
            },
            success: function(data){
                if(data == "none")
                {
                    sInfo.html("<font color='red'>No Surname Entered</font>");
                }
                else if(data != "0")
                {
                    sInfo.html("<font color='red'>Surname Exists</font>");
                }
                else
                {
                    sInfo.html("<font color='green'>Surname Not Found</font>");
                }
            }
        });
    }); 

check.php:

//database connection stuff

extract($_REQUEST);

if(!empty($sName))
{
    $sql = "SELECT sName FROM student WHERE sName='$sName'";
    $rsd = mysqli_query($DBConnect, $sql) or die('Error: '.mysqli_error($DBConnect));
    $msg = mysqli_num_rows($rsd); 
    mysqli_free_result($rsd);
    mysqli_close($DBConnect);
}
else
{
    $msg = "none";
}
echo $msg;

No matter what the value of data is (eg "1", "2", "0", "none") the sInfo div always displays "Surname Exists".

When I change it to display

else if(data != "0")
                    {
                        sInfo.html("<font color='red'>Surname Exists..."+data+"</font>");
                    }

The result is Surname Exists...0 or Surname Exists...none when it should instead display No Surname Entered or Surname Not Found...

What am I doing wrong?

thanks.

  • 写回答

1条回答 默认 最新

  • dongyao9762 2013-05-22 01:38
    关注

    Change the line

    data: "sName="+$(this).attr("value"),
    

    to

    data: {"sName":$(this).attr("value")},
    

    jquery will format it correctly in the post body

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的代码运行
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败