dspx15491 2012-07-04 16:54
浏览 38
已采纳

使用PHP的jQuery AJAX响应很难

I am fairly new to AJAX. I am trying to get a simple login script to work. This is using jQuery 1.6.4. In the AJAX below, when the user clicks a button, it sends the email address and password to login.php. That all seems to work fine. The trouble is with the success function. When the email and password are correct, it should return true. It should return false when it does not work. Using Firebug, I see that it works with console.log. It also works correctly if I write alert(response);. However, the conditional always evaluates to false even when response is equal to true. I've tried both if(response=="true") and if(response==="true"), putting the variable outside the function, and a few other things without success. Would anyone have any ideas on how to fix this?

Thank you for any help or ideas, Jason.

AJAX:

$("#firstpage").live('pageinit', function (evt) {
$('#button').click(function(){       
var $form = $('#login'),
$inputs = $form.find("input"),
serializedData = $form.serialize();
$.ajax({
  type: 'POST',
  url: 'php/login.php',
  data: serializedData,
  success: function(response){
    console.log("Response: "+response);
    if(response=="true") 
    {
$('#firstpage #wrong').text("Login script is working");
} else {
$('#firstpage #wrong').text("Your email and password combination did not match.");
}

    },      
  dataType: 'json'
});
});  
});

If it helps, this is my login.php script.

$email = $_POST['email'];
$password = $_POST['password'];
require_once("DB.php");
$connection = mysql_connect($host, $user, $pass) or die ("Unable to connect!"); 
mysql_select_db($db) or die ("Unable to select database!"); 

$query = "SELECT * FROM member WHERE email='$email' AND password='".md5($_POST['password'])."'";
$result = mysql_query($query) or die ("Error in query: $query. ".mysql_error()); 

$num_rows = mysql_num_rows($result);
if($num_rows>0){
$output = true;
} else {
$output = false;
}
echo json_encode($output);
  • 写回答

2条回答 默认 最新

  • dongtu0363 2012-07-04 17:02
    关注

    The response is an object because you have "dataType: 'json'". jQuery will try and convert the responseText to JSON. If you need to check the data the server returned, try using

    if (response === true) {
    
    }
    

    or simply

    if (response) {
    
    }
    

    or just have jQuery return the string by removing the datatype: 'json'

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码