jQuery提交功能不起作用(内部功能) [英] jQuery Submit Function Does Not Work (Inner Function)
问题描述
我对这个jQuery代码有疑问.它不能按预期工作:
I have a problem with this jQuery code. It doesn't work as expected:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit( function(event){
$.post("list.php", { name: "John", time: "2pm" },
function(data) {
alert("Data Loaded: " + data);
});
});
});
但是,这可行:
$('#select_dropdown').change ( function(){
$('#form_to_submit').submit();
});
我想知道为什么提交的内部功能不起作用.当用户从下拉列表中选择一个值时,必须提交表单.第二组代码有效,但是如果我添加内部函数来提交,则不会.
I wonder why the internal function on submit doesn't work. When a user selects a value from a dropdown, the form must be submitted. The second set of codes work but if I add an inner function to submit, it doesn't.
基本上,我想在用户在下拉菜单中选择之后进行一些Ajax调用.
Basically, I want to do some ajax call after the user select on the dropdown.
推荐答案
根据文档( http://api .jquery.com/submit/),不带参数的submit()
会提交您的表单,但是如果包含参数,它将把submit
事件绑定到表单,但不会提交.
According to documentation ( http://api.jquery.com/submit/ ), submit()
without parameters will submit your form, but if you include arguments it will bind the submit
event to the form, but it wont submit it.
因此,@ Chris Fulstow发布的代码将是提交表单的正确方法,但是由于ajax不同步,因此函数将继续运行而无需等待答案,然后将不显示警报.
So, the code posted by @Chris Fulstow would be the right way of submitting the form, but as ajax is not synchronous, function will continue without waiting for the answer and then, the alert will not be shown.
您可以使其同步,但是必须使用$.ajax
而不是$.post
,因为$.post
不包括async
选项.无论如何,我正在为您的特定问题提供解决方案,但我想应该有更好的解决方法.
You can make it synchronous, but you must use $.ajax
instead of $.post
, because $.post
doesn't include an async
option. Anyway, I'm providing a solution for your specific problem, but I'm guess there should be a better way for doing it.
$(function() {
$('#select_dropdown').change(function() {
$('#form_to_submit').submit();
});
$('#form_to_submit').submit(function(event) {
$.ajax(
url: "list.php",
data: { name: "John", time: "2pm" },
success: function(){
alert("Data Loaded: " + data);
},
async:false,
);
});
});
这篇关于jQuery提交功能不起作用(内部功能)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!