[英]jQuery - how to get the value of an input of type submit when ajaxifying a form
Suppose I have the following code:假设我有以下代码:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd"
>
<html lang="en">
<head>
<title><!-- Insert your title here --></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#form1').submit(function(){
// Let's see the values
alert($(this).serialize());
$.post($(this).attr('action'), $(this).serialize(), function(data){
// Do something on callback
});
return false;
})
});
</script>
</head>
<body>
<form action="http://example.com/bla" method="POST" id="form1">
<input type="hidden" name="ipt1" value="1"/>
<input type="submit" name="sbt" value="2"/>
</form>
</body>
</html>
When I serialize the form's values the value of the input type submit clicked is not there.当我序列化表单的值时,输入类型的值 submit clicked 不存在。 How do I handle this kind of situation when ajaxifying my forms? ajax化我的表单时如何处理这种情况?
In non-ajax forms the value of the submit button is only sent with the form, if it is clicked.在非 ajax 表单中,提交按钮的值仅在单击时随表单一起发送。 So if you want to mimic this behaviour with ajax you have to do it something like this:所以如果你想用 ajax 模仿这种行为,你必须这样做:
$("#submit_button").click(function() {
var data = $("#my_form").serialize();
data += data.length ? "&" : ""; // check if empty
data += escape($(this).attr("name"))+"="+escape($(this).val());
// ...
return false;
});
This appends the serialized data of the submit button to the serialized form data.这会将提交按钮的序列化数据附加到序列化表单数据。
This is by design.这是设计使然。 the .serialize()
method does not serialize inputs of type submit
. .serialize()
方法不会序列化submit
类型的输入。
Unfortunately the way you have it you would not be able to access the source of the event.不幸的是,您将无法访问事件的来源。 Your best bet is to wire all the submits, and then append the source data like this:最好的办法是连接所有提交,然后像这样附加源数据:
$('input:submit').bind('click', function(){
var data = $("#form1").serialize();
data += "&"+escape($(this).attr("name"))+"="+escape($(this).val());
alert(data);
$.post($('#form1').attr('action'), data, function(data) {
//do something
});
return false;
});
I am using the following solution:我正在使用以下解决方案:
<input type="radio" name="action" value="action_1" style="display:none"></input>
<button type="submit" onclick="this.previousElementSibling.checked=true" >Do Action 1</button>
You repeat this for any number of choices (name, value), and the form is submitted as soon as you choose one.您对任意数量的选项(名称、值)重复此操作,并在您选择一个后立即提交表单。 Make sure the page is reloaded after use.确保页面在使用后重新加载。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.