php - ajax POST 不起作用,不明白为什么

标签 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",
            data: "?id="+the_id,
            url: "vote.php",
            success: function(msg)
            {
                $("span#message"+the_id).html(msg);
            }
        });
    });
});

我的 vote.php 如下所示:

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 method="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。查看 jquery API 上的示例页面以获取更多信息!

关于php - ajax POST 不起作用,不明白为什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4060749/

相关文章:

JavaScript 警报弹出框未被调用

javascript - 我在特定屏幕尺寸下禁用了特定 jQuery 脚本,但是如何在调整屏幕大小时检查它?

javascript - .attr ('checked' , true) 不会在按钮点击时重新添加

javascript - 在html中调用js函数

php - Laravel 错误不起作用

php - 通过 ajax 到 PHP 的多维数组

php - 在重定向到 Paypal 之前提交表格

javascript - 如何仅使用 onload 函数而不是 javascript 删除 iframe 中的类

php - 从文件夹 PHP 中删除图像

javascript - 使用 Scrollify 获取上次查看的索引