我在html页面中有两个链接。当用户点击其中一个链接时,我想获取链接的ID并使用表单数据提交。
我的html页面是这样的:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
var selectedForm = 0;
window.onload = function() {
$(".respondButton").on('click', function(e) {
var selectedButton = $(this).attr('id');
selectedForm = selectedButton.replace('response', '');
console.log(selectedForm);
});
document.getElementById("submitButton1").onclick = function() {
doWork()
};
}
function doWork() {
var response = $('#reply1').val();
console.log(response);
$.post({url: "receiver", data: JSON.stringify({selectedForm: selectedForm, response : response}),
contentType: "application/json", success: function(){}});
event.preventDefault();
}
</script>
This will send data using AJAX to Python:<br /><br />
<a id="response1" href="" class="respondButton">
<span>response1</span>
</a>
<a id="response2" href="" class="respondButton">
<span>response2</span>
</a>
<form action="/receiver" method="post" id="form1" name="form1">
<textarea type="text" rows ="3" name="reply1" id="reply1"></textarea>
<button type="submit" name="submitButton1" id="submitButton1">Gönder</button>
</form>
当我点击其中一个链接时,输入一些表单数据并单击提交按钮selectedForm始终为0.
如何获取所点击链接的ID并使用表单数据提交。
更新
使用$(document).ready(function(){})之后;而不是window.onload它现在按预期工作。
答案 0 :(得分:2)
您的代码按原样为我工作,但我会建议进行一些更改以使其清理并使其更好地运行:
$(function() {
var selectedForm = 0;
function doWork() {
var response = $('#reply1').val();
console.log(response);
$.post({url: "receiver", data: JSON.stringify({selectedForm: selectedForm, response : response}),
contentType: "application/json", success: function(){}});
}
$('.respondButton').click(function(e) {
e.preventDefault();
var selectedButton = $(this).attr('id');
selectedForm = selectedButton.replace('response', '');
console.log(selectedForm);
});
$('#submitButton1').click(function(e) {
e.preventDefault();
doWork();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<a id="response1" href="" class="respondButton">
<span>response1</span>
</a>
<a id="response2" href="" class="respondButton">
<span>response2</span>
</a>
<form action="/receiver" method="post" id="form1" name="form1">
<textarea type="text" rows ="3" name="reply1" id="reply1"></textarea>
<button type="submit" name="submitButton1" id="submitButton1">Gönder</button>
</form>