Ajax到php的调用不成功


Ajax to php call isn't successful

我试着测试一个ajax调用的post只是为了测试的目的,但由于某种原因,调用从来没有成功。我一直在寻找,并没有找到太多可以解释为什么这不起作用的原因。

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

file.php包含以下内容:

<?php 
    return true;
?>
谁能给我指个正确的方向?我知道这可能看起来很简单,但我被难住了。谢谢。

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

echo 'true';

首先检查路径。是file.php居住在同一文件夹的文件,你的javascript是包含在?

如果你的路径不正确,如果你使用chrome浏览器,你会得到一个404错误打印到你的javascript控制台。

你也应该把你的php改成:

<?php
echo 'true';

一旦你的路径是正确的,你的php修改,你应该很好去。

您是否尝试过直接访问文件并查看它是否输出某些内容?

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

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

编辑:另外,不要通过比较检查,只需对'data'发出警告,看看它得到了什么

除了提示回显'true'之外,您还可以尝试提醒返回给ajax的实际数据。这样你就可以知道你是否为你的if语句设置了合适的值/类型。

success: function(data) {
    alert(data);
}

试试这个,新的ajax语法

$.ajax({ type: "POST", url: "file.php" }).done(function(resp){
    alert(resp);
});

正确的方法是:

$.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
?>