1

我只是无法让它工作,因为我在 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 似乎无法识别它......

任何帮助将不胜感激!

4

2 回答 2

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';
}
于 2013-07-05T13:20:16.740 回答
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';

它工作得很好。

版本jquery.min.js是 1.7.1

于 2013-07-05T13:48:27.127 回答