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

时间:2013-07-05 12:58:47

标签: 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

所以foo被正确设置为'ok'(如console.log中所示),但是if / else似乎没有认出它......

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:4)

@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';
}

答案 1 :(得分:0)

尝试使用此代码

<!DOCTYPE html >
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Stack Tester</title>
  <script src=jquery.min.js type="text/javascript"></script>
  <script type="text/javascript">
     //<![CDATA[
        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
                    }
                }
            });
        }
     //]]>
  </script>
</head>
<body>
  <script type="text/javascript">
      //<![CDATA[
        check_foo();
      //]]>
  </script>   
</body>
</html>

使用ajax.php

<?php
echo 'ok';

它工作正常。

<{1}}的

版本为1.7.1