ajax sucess:我无法检查返回的信息是真还是假

当我尝试检查返回的信息是真还是假时,我遇到了问题。 在console.log中返回true但总是进入其他…

$.ajax({ url: "ajax.php", type: 'POST', data: 'act=login&email=' + email + '&password=' + password + '&remember=' + remember, success: function(data) { console.log(data); if (data.success === true) { $("#login-form")[0].reset(); window.location.replace('dashboard.php'); } else { $(".error-message span").html('Please, insert valid data.'); $('.error-message').fadeIn('slow', function () { $('.error-message').delay(5000).fadeOut('slow'); }); } } }); 

感谢大家。

Console.log打印data

您的IF语句检查`data.success’。 这是两个不同的元素。

您以什么格式从ajax.php发回数据?

您不能假设数据是数组或JSON对象,您必须先解析它。

 json = JSON.parse(data); if (json.success === true) {} //or if (json === true) depends on the response from ajax.php 

根据您的评论,如果您返回的数据只是真或假,只需使用

 if (data == true) {//I use double and not triple equality because I do not know if you are returning a string or a boolean. } 

你有两个问题:

  1. 您正在尝试访问data.success而不仅仅是数据。
  2. 你正在使用严格的比较(===),我真的不确定你的返回数据是否是布尔值而不是字符串。 @Pekka的回答也提到了它(但由于data.success不存在,它不会起作用)。

希望这可以帮助!

返回值可能是字符串true ,而不是JavaScript布尔值true

因为您使用的是严格的===比较,它需要相同的变量类型,所以它总是会失败。

比较字符串:

 if (data.success == "true") 

如果您的数据看起来像{"success": true}那么它可能是数据解析的问题,其中ajax处理程序没有将响应解析为json数据..而只是传递一个字符串。

因此,尝试将dataType属性设置为json以告诉ajax您期望json响应。

 $.ajax({ url: "ajax.php", type: 'POST', data: 'act=login&email=' + email + '&password=' + password + '&remember=' + remember, dataType: 'json', success: function (data) { console.log(data); if (data.success === true) { $("#login-form")[0].reset(); window.location.replace('dashboard.php'); } else { $(".error-message span").html('Please, insert valid data.'); $('.error-message').fadeIn('slow', function () { $('.error-message').delay(5000).fadeOut('slow'); }); } } }); 

你有没有尝试过 ?

if(data.success ==’true’){……}

或者如果它以“Json”格式出现,您需要在“成功”事件中转换为这样的对象。 (包括json.js)

 var JSONfoo = JSON.stringify(data); obj = eval('(' + JSONfoo + ')'); if(obj != null){ alert(obj.success ); 

}

昨天以构建解决方案的formsjson = JSON.parse (data); 工作,但现在另一种forms给我一个错误( Uncaught SyntaxError: Unexpected token < )on line json = JSON.parse (data);

我不明白在表格上工作的原因而不是另一个表格!

在ajax.php中,我返回一个echo "true";

谢谢你们