繁体   English   中英

如何获得我的jquery帖子请求以与单击中从函数存储的变量一起使用?

[英]How do I get my jquery post request to work with the variable stored from a function on a click?

我一直在撞墙,试图在用户单击按钮后立即将游戏名称传递给我的php函数。 这个想法是用户单击一个按钮,该按钮具有其视频游戏名称的值,然后php脚本检查该游戏的排名并将该排名返回给html。 我以前曾要求发布请求,即使在这里,当我手动将变量名设置为游戏之一来测试它时,它也可以工作。 请帮忙!

<script>
$(document).ready(function(){
    //global n variable
    n = $();

        $('#target').click(function(){
            //set value of n to the game's name
                n = $(this).val();

        });

        //then send the name as term to my php function to deal with it and return 
        //the ranking
    $.post('getTotal.php', {term: n}, function(data){
        //been trying to see if anything comes through for debugging purposes
                alert(data);

        //commented this out for now, just puts it in the div I left open
        //$('#total').html(data);
    });

});

</script>

您应该将$.post放入您的点击处理程序中,以便它仅在您实际单击按钮时才会运行...现在您的代码设置了一个n变量,其值是一个空的jQuery对象(为什么?)。 然后,它在按钮上附加一个单击处理程序。 然后,它运行$.post请求n仍然是一个空的jQuery对象。 单击按钮的时间要晚得多...

另外,应避免使用全局变量。 声明变量时应使用var关键字。

仅当用户单击按钮时。 在点击处理程序中,获取值并执行http发布

$ ajax或$ POST

例如-

$(document).ready(function() {
      $('#target').click(function()
            $.ajax({  
              type: "POST",
              url: "url...",
              data: "n="+nVal+",
              success: function(html){
                alert( "Submitted");
              }
           });
      });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM