使用按钮输入和 jQuery 提交表单
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12068471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Submit form with button input and jQuery
提问by Mohammad Saberi
I have a form like this :
我有一个这样的表格:
<form id="myform" action="something.php" method="post">
<input type="text" name="first_name" /><br />
<input type="button" id="submit" value="Send" />
</form>
I want to submit this form after getting successful message from some processes in JavaScript and jQuery. So I did it like this :
我想在从 JavaScript 和 jQuery 中的某些进程获得成功消息后提交此表单。所以我这样做了:
$(document).ready(function(e) {
$('#submit').click(function(event){
event.preventDefault();
$.post('process/process.php',
{
// I passed data here
},
function(data) {
if (data.result == '1') {
$('#myform').submit();
} else {
alert('Error #'+data.result+' occurred!');
}
},
'json'
);
});
});
But even after getting data.result == '1'
, the submitting form does not work. What's the problem here ?
但即使在得到 之后data.result == '1'
,提交表单也不起作用。这里有什么问题?
Edit:
编辑:
I've changed jQuery to :
我已将 jQuery 更改为:
$(document).ready(function(e) {
$('#submit').click(function(event){
$('#myform').submit();
)};
)};
So there is no condition now, but form did not submit.
所以现在没有条件,但表单没有提交。
回答by Amith George
From the jQuery documentation for .submit()
,
从 jQuery文档中.submit()
,
Additional Notes:
Forms and their child elements should not use input names or ids that conflict with properties of a form, such as submit,length, or method. Name conflicts can cause confusing failures. For a complete list of rules and to check your markup for these problems, see DOMLint.
补充说明:
表单及其子元素不应使用与表单属性(例如提交、长度或方法)冲突的输入名称或 ID。名称冲突会导致令人困惑的失败。有关完整的规则列表并检查您的标记是否存在这些问题,请参阅 DOMLint。
Rename the id of the second input to submitForm
or something similar.
将第二个输入的 id 重命名为submitForm
或类似的名称。
Working fiddle: http://jsfiddle.net/WvSdX/
工作小提琴:http: //jsfiddle.net/WvSdX/
回答by Mohammed Swillam
I think it's a matter of a value-comparison issue here. to give us a better way to determine if this is the case, can you temprorly change the callback to this and give it a try?
我认为这是一个价值比较问题。为了给我们一个更好的方法来确定是否是这种情况,您能否暂时将回调更改为 this 并尝试一下?
$(document).ready(function(e) {
$('#submit').click(function(event){
event.preventDefault();
$.post('process/process.php',
{
// I passed data here
},
function(data) {
$('#myform').submit();
},
'json'
);
});
});
if the form get submitted, then there is nothing wrong with the jQuery part, it's a matter of correctly getting the result out of your post() operation.
如果表单被提交,那么 jQuery 部分就没有问题,这是正确地从 post() 操作中获取结果的问题。
Please give it a try and let me know if it's working or not.
请试一试,让我知道它是否有效。