php - 使用 $.ajax() 响应 if else 语句

标签 php javascript jquery ajax

我只是无法让它工作,因为我在 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/

相关文章:

javascript - Firefox 何时可能实现 lengthAdjust 和 textLength 有什么想法吗?

jquery - 如何使用 jQuery 重载 focusOut?

jquery - 如何使用来自不同图像文件的一个图标?

php - 什么是 PDO 可滚动游标?

php - cordova.js 无法在远程页面上工作

javascript - nuxt.js - 预加载 .woff 字体加载为 @font-face

javascript - 禁用数据列表中的元素

javascript - 无法使用ssl在php中读取cookie

php - 有时 mysql 全文搜索在应该返回任何结果时却没有返回任何结果

javascript - 404 使用 attach() 时 Strophe 中的 SID 值无效