我正在制作一个笑话网站。每个笑话都存储在 mysql 数据库的一条记录中。当笑话放在页面上时,会出现一个带有 class=votebutton
的投票按钮。当有人单击此按钮时,我希望通过 jquery 的 ajax 函数将表单的 id 和用户的 IP 地址发送到我的投票处理 .php 文件。我有两个问题:
1. 使用 $(".votebutton").click()
作为选择器来运行此函数是否正确?
2. 如何选择正在提交的表单的id
来构造jquery函数中的id变量?
$(function() {
$(".votebutton").click(function() {
var id = //I'd like this to be the id of the form submitted
var ip = //I'd like this to be the ip of the user
var dataString = 'id='+ id = '&ip=' + ip;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "bin/vote.php",
data: dataString,
success: function() {
//something to do on success
}
});
return false;
});
});
另外,如果你们有时间的话,还有一个问题 - 获取访问者 IP 的好方法是什么。我预计每页大约有 10 个这样的表格(每个笑话一个)...
非常感谢您的帮助...
最佳答案
Is it right to use $(".votebutton").click() as the selector
是的
How do I select the id of the form being submitted
常见的做法是将 ID 存储为元素 ID 的一部分,例如:
<button id="vote_54321" value="Vote!" class="votebutton" />
然后,在您的函数中您可以获得 ID:
var id = $(this).attr('id').split('_')[1];
无法从 javascript 获取客户端 IP,您应该在服务器端 php 代码中获取它:
$userip = $_SERVER['REMOTE_ADDR'];
关于php - 选择提交表单的id以放入jquery变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5229478/