我一直在试图得到这个使用AJAX与JQuery和PHP一起工作没有运气(here's the page for the sample)的非常简单的例子。我已经看了不少有类似dispost的帖子,但都没有帮助...AJAX不工作的JQuery/PHP调用
我已经复制了代码,但我的功能应该在成功上运行,永远不会被调用。作为一个实验,在$ .post的调用中,我注释了数据部分({sendValue:str})和JSON部分,并在成功函数的主体中添加了一条警报,以查看它是否被调用并且是。所以我猜猜我的数据创建有什么问题?我还尝试在警报中显示AJAX调用返回的数据,并将其显示为“未声明”(data.returnValue)。
这是我的代码的副本,您可以通过上面也是一个工作示例的链接从教程这里笔者看到完整的例子:http://www.devirtuoso.com/Examples/jQuery-Ajax/
JQuery的:
$(document).ready(function(){
$('#txtValue').keyup(function(){
sendValue($(this).val());
});
});
function sendValue(str){
$.post("ajax.php",
{ sendValue: str },
function(data){
$('#display').html(data.returnValue);
},
"json"
);
}
PHP :
<?php
//Get Post Variables. The name is the same as
//what was in the object that was sent in the jQuery
if (isset($_POST['sendValue'])){
$value = $_POST['sendValue'];
}else{
$value = "";
}
//Because we want to use json, we have to place things in an array and encode it for json.
//This will give us a nice javascript object on the front side.
echo json_encode(array("returnValue"=>"This is returned from PHP : ".$value));
?>
HTML:
<body>
<p>On keyup this text box sends a request to PHP and a value is returned.</p>
<label for="txtValue">Enter a value : </label><input type="text" name="txtValue" value="" id="txtValue">
<div id="display"></div>
</body>
谢谢!
编辑: 我重写了我的$ .post到一个$ .ajax与它的错误函数。我肯定打了错误的功能,错误是一个解析错误 - 我猜它是来自我的PHP脚本,当我打电话给json_encode ...这是萤火虫的截图 - 任何人有更多的想法?:
Screenshot 1 - firebug console
Screenshot 2 - firebug watch window
感谢所有帮助迄今为止的方式,真的很感激。
您是否在PHP的早期尝试了echoing或var_dumping,然后退出以查看您的发布后调用是否将其发送到适当的位置(ajax.php)? – csjohn
@csjohn我会给你一个去吧,让你知道发生了什么... –
你的代码中你有ajax.php - 这是读取值?如果不是,请告诉我们真正的价值是什么? – ManseUK