[英]How do I get my jquery post request to work with the variable stored from a function on a click?
I have been banging my head against the wall trying to pass a game's name through to my php function as soon as a user clicks a button. 我一直在撞墙,试图在用户单击按钮后立即将游戏名称传递给我的php函数。 The idea is the user clicks a button, which has a value of its videogame name, then the php script checks that game's ranking and returns that ranking to the html. 这个想法是用户单击一个按钮,该按钮具有其视频游戏名称的值,然后php脚本检查该游戏的排名并将该排名返回给html。 I have made post requests work before, and even here when I manually set the variable name to one of the Games to test it, it works. 我以前曾要求发布请求,即使在这里,当我手动将变量名设置为游戏之一来测试它时,它也可以工作。 Please help! 请帮忙!
<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>
You should put the $.post
into your click handler... so it will only run when you actually click the button... now your code sets up an n
variable, its value is an empty jQuery object (why?). 您应该将$.post
放入您的点击处理程序中,以便它仅在您实际单击按钮时才会运行...现在您的代码设置了一个n
变量,其值是一个空的jQuery对象(为什么?)。 Then it attaches a click handler on the button. 然后,它在按钮上附加一个单击处理程序。 Then it runs a $.post
request - n
is still an empty jQuery object. 然后,它运行$.post
请求n
仍然是一个空的jQuery对象。 Clicking the button happens much later... 单击按钮的时间要晚得多...
Also, using globals should be avoided. 另外,应避免使用全局变量。 The var
keyword should be used when declaring variables. 声明变量时应使用var
关键字。
simply when the user clicks the button. 仅当用户单击按钮时。 inside the click handler, obtain the value and perform an http post 在点击处理程序中,获取值并执行http发布
$ajax or $POST $ ajax或$ POST
eg - 例如-
$(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.