我只是无法让它工作,因为我在 if/else 语句中使用 ajax 调用的响应。如果我在 console.log() 中输出响应,则表明它设置正确,但简单的 if/else 语句不起作用。
function check_foo() {
dataString = {action: 'do_this'};
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
success: function(foo) {
console.log('foo='+foo); // output: foo=ok
if (foo=="ok") { // should be true, but isn't
console.log('foo='+foo+' -> OK');
} else { // instead this gets output
console.log('foo='+foo+' -> FAIL'); // output: foo=ok -> FAIL
}
}
});
}
check_foo();
ajax.php:
echo 'ok'; // This is the result of the call
so foo 被正确设置为“ok”(如 console.log 中所示),但 if/else 似乎无法识别它...
任何帮助将不胜感激!
最佳答案
@johan 评论对你来说是完美的答案,我已经尝试过了:- 使用trim() function.js:-
function check_foo() {
dataString = {action: 'do_this'};
jQuery.ajax({
type: "POST",
url: "response.php",
data: dataString,
success: function(foo) {
if (jQuery.trim(foo) == "ok") {
alert(foo);
} else {
alert('jgjhg');
}
}
});
}
现在 ajax.php:-
if($_REQUEST['action'] == 'do_this') {
echo 'ok';
}
关于php - 使用 $.ajax() 响应 if else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17489513/