我尝试在输入邮政编码后自动提交表单,这将触发谷歌地图的显示。
如果我使用表单的提交按钮,代码工作正常。表单提交,ajax代码执行此操作,div替换为与邮政编码对应的Google地图。
但是,如果我尝试使用以下代码自动提交表单:
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#htmlExampleTarget' // target element(s) to be updated with server response
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// bind to the form's submit event
$('#htmlForm').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
});
<form id="htmlForm" action="html-echo.php" method="post">
Message: <input type="text" name="message" onKeyUp="if(this.value.length>4)this.form.submit()">
<div id="htmlExampleTarget">
<script type="text/javascript">
$(function()
{
$("#map").gMap({ address: "Los Angeles", zoom: 13 });
});
</script>
<div id="map" style="width: 547px; height: 320px; border: 1px solid #777; overflow: hidden;"></div>
</div>
// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit
// $.ajax options can be used here too, for example:
//timeout: 3000
};
// bind to the form's submit event
$('#htmlForm').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
所有这一切都是加载了表单action(action =“html-echo.php”)页面。
如何使this.form.submit的行为与提交按钮相同?
谢谢!
答案 0 :(得分:0)
DOM方法form.submit()
不会触发提交处理程序。由于您使用的是jQuery,请改用$(this.form).trigger("submit")
。