【问题标题】:ajax POST not working, can't figure whyajax POST 不工作,不知道为什么
【发布时间】:2010-10-31 05:57:15
【问题描述】:

我有一个简单的 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 方法="post",它会正确更新数据库。

谁能看出问题所在?

谢谢

【问题讨论】:

    标签: php javascript jquery ajax


    【解决方案1】:

    您尝试在 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 页面上的示例以获取更多信息!

    【讨论】:

      【解决方案2】:

      我在您的代码中看到的看起来不正确的主要内容是data: "?id="+the_id,? 是不必要的,并且对于发布请求不合逻辑。请改为执行以下操作:

      data: {
          id: the_id
      }
      

      这让 jQuery 为你做 URL 编码。

      另外一点,您可以使用$(this).attr(id)。这是非常低效的。改为使用this.id,以获得完全相同的效果快数百倍 at least 20 times quicker

      【讨论】:

        【解决方案3】:

        您的 data 值不应需要以问号开头。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-02-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多