[英]Ajax to php call isn't successful
我正尝试通过执行以下仅出于测试目的来测试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;
?>
有人能指出我正确的方向吗? 我意识到这似乎很简单,但我很沮丧。 谢谢。
return true
将使脚本退出。 你需要:
echo 'true';
首先检查您的路径。 file.php
是否与javascript所在的文件位于同一文件夹中?
如果您的路径不正确,那么如果您使用的是Chrome浏览器,则会在javascript控制台上显示404错误。
另外,您应该将您的php更改为:
<?php
echo 'true';
一旦您的路径是正确的并且您的php被修改了,您应该就可以了。
您是否尝试过直接访问该文件并查看其是否输出某些内容?
在这种情况下不应该使用return true(或其他情况,最好使用exit或die),通过AJAX调用获得的所有内容都是服务器端生成的超文本,您应该使用(因为它们在echo'true'之前指出了您的意思) ;)
如果问题仍然存在,您还可以尝试使用传统的AJAX调用XMLHttpRequest(不使用JQuery),然后检查请求和服务器之间是否存在任何问题。
编辑:另外,不要通过比较进行检查,只是对“数据”发出警报以查看它得到了什么。
除了回显“ 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
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.