Php ajax POST不工作,可以';我不明白为什么
我有一个简单的AJAX函数,可以将对象的id发送到php页面 我的函数如下所示:Php ajax POST不工作,可以';我不明白为什么,php,javascript,jquery,ajax,Php,Javascript,Jquery,Ajax,我有一个简单的AJAX函数,可以将对象的id发送到php页面 我的函数如下所示: $(function(){ $("a.vote").click(function(){ //get the id the_id = $(this).attr('id'); alert(the_id); //ajax post $.ajax({ type: "POST",
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
My vote.php如下所示:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
当我执行AJAX函数时,vote.php似乎从未运行过
我知道我的AJAX函数被正确调用,因为alert(the_id);正在弹出正确的ID
我知道我的vote.php功能正常,因为我可以运行一个名为“id”的文本框的HTML方法=“post”,它将正确更新数据库
有人知道怎么了吗
谢谢您试图在URL中发送变量,而不是作为POST变量。应该是这样的:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
您的数据应该作为对象而不是字符串URL包含。查看页面上的示例,了解更多信息 您的
数据
值在开始时不需要问号。我在您的代码中看到的主要错误是数据:“?id=“+the_id,
”。?
是不必要的,对于post请求来说是不合逻辑的。请改为执行以下操作:
data: {
id: the_id
}
这使jQuery可以为您进行URL编码
另外一点是,您需要执行$(this).attr(id)
。这是非常低效的。改为使用this.id
,以更快数百倍的速度获得完全相同的效果