这是index.php
post_data = {'username':username, 'old_pass':old_pass, 'new_pass':new_pass};
$.post('change_pass.php', post_data, function(result) {
if(result.text == 'success') {
$("#message").text("Password changed successfully");
} else {
$("#message").text("Error changing password");
}
}, 'json');
并且change_pass.php是
<?php
@mysql_connect("localhost","root","") or die('Connection problem');
@mysql_select_db("my_db");
$username = filter_var($_POST["username"], FILTER_SANITIZE_STRING);
$old_pass = filter_var($_POST["old_pass"], FILTER_SANITIZE_STRING);
$new_pass = filter_var($_POST["new_pass"], FILTER_SANITIZE_STRING);
if(mysql_num_rows(mysql_query("UPDATE `users` SET `pass`='".$new_pass."' WHERE `pass`='".$old_pass."' AND `user`='".$username."'")) == 1) {
$output = json_encode(array('text' => 'success'));
die($output);
} else {
$output = json_encode(array('text' => 'failure'));
die($output);
}
?>
密码更改成功,但回调无效。为什么呢?
但如果我避免查询,回调就有效。所以当我使用查询时,我认为出了问题。
答案 0 :(得分:2)
如果我没记错的话,PHP json_encode(array())
- 函数返回一个包装在数组中的JSON对象。像这样:
[{text: 'success'}]
因此ajax结果将是:
$.post('change_pass.php', post_data, function(result) {
if(result[0].text == 'success') {
$("#message").text("Password changed successfully");
} else {
$("#message").text("Error changing password");
}
}, 'json');
试试看?另外:我不确定用die()
中止页面是否是最好的办法。我建议你回应结果,然后返回。像这样:
echo json_encode(array('text' => 'success'));
return;
修改强> 然后我建议你重新格式化你的ajax请求更像这样:
$.post( 'change_pass.php', post_data)
.done(function( result ) {
// Check what result will get you in the console (Ctrl + Shift + J in chrome)
console.log(result);
});
答案 1 :(得分:1)
将您的代码更改为:
if(mysql_num_rows(mysql_query("UPDATE `users` SET `pass`='".$new_pass."' WHERE `pass`='".$old_pass."' AND `user`='".$username."'")) == 1) {
$output = json_encode(array('text' => 'success'));
echo $output;
return;
} else {
$output = json_encode(array('text' => 'failure'));
echo $output;
return;
}