1

我正在尝试通过执行以下操作来测试 post 上的 ajax 调用,但出于某种原因,该调用永远不会成功。我一直在四处寻找,找不到太多可以解释为什么这不起作用的东西。

$.ajax({
    type: "POST",
    url: "file.php",
    success: function(data) {
        if(data == 'true'){
            alert("success!");
        }
    },
    error: function(data) {
        alert("Error!");
    }});

file.php 包含以下内容:

<?php 
    return true;
?>

有人可以指出我正确的方向。我意识到这可能看起来很简单,但我很难过。感谢。

4

6 回答 6

5

return true将使脚本退出。你需要:

echo 'true';
于 2013-06-04T00:27:59.930 回答
0

这是正确的方法:

$.ajax({
    type : "POST",
    url : "file.php",
    success : function (data) {
    /* first thing, check your response length. If you are matching string
       if you are using echo 'true'; then it will return 6 length,
       Because '' or "" also considering as response. Always use trim function
       before using string match. 
    */
        alert(data.length);
        // trim white space from response
        if ($.trim(data) == 'true') {
            // now it's working :)
            alert("success!");
        }
    },
    error : function (data) {
        alert("Error!");
    }
});

PHP代码:

<?php 
echo 'true'; 
// Not return true, Because ajax return visible things.
// if you will try to echo true; then it will convert client side as '1'
// then you have to match data == 1
?>
于 2013-06-04T07:19:10.097 回答
0

您是否尝试过直接访问该文件并查看它是否输出了什么?

在这种情况下不应该使用 return true (或任何其他情况,最好使用 exit 或 die),通过 AJAX 调用获得的所有内容都是服务器端生成的超文本,您应该使用(正如他们在 echo 'true' 之前指出的那样) ;)

如果问题仍然存在,您也可以尝试传统的 AJAX 调用 XMLHttpRequest(不带 JQuery),然后检查请求和服务器之间是否有任何问题。

编辑:另外,不要比较检查,只需提醒“数据”看看它得到了什么。

于 2013-06-04T01:08:47.620 回答
0

除了 echo 'true' 建议之外,您还可以尝试提醒返回给 ajax 的实际数据。这样您就可以查看您的 if 语句是否具有正确的值/类型。

success: function(data) {
    alert(data);
}
于 2013-06-04T01:51:36.773 回答
0

试试这个,新的 ajax 语法

$.ajax({ type: "POST", url: "file.php" }).done(function(resp){
    alert(resp);
});
于 2013-06-04T06:19:10.323 回答
0

首先检查你的路径。是否file.php与您的 javascript 所在的文件位于同一文件夹中?

如果您的路径不正确,如果您使用的是 chrome,您的 javascript 控制台会打印 404 错误。

此外,您应该将您的 php 更改为:

<?php

echo 'true';

一旦你的路径是正确的并且你的 php 被修改了,你应该很高兴。

于 2013-06-04T00:31:21.280 回答