1、ajaxForm
作用:
(1)预加载js事件到form
(2)提交action前js验证表单
(3)提交action后,结果由js处理,不自动跳转
要求:
<script type="text/javascript" src="js/jquery-2.1.1.min.js"></script> <script type="text/javascript" src="js/jquery.form.js"></script>
示例:
<script type="text/javascript"> //var error = document.getElementById('errorDiv'); //注意的是var error只在这里声明,不要赋值 ,赋值也是null var error; // wait for the DOM to be loaded $(document).ready(function() { error = document.getElementById('errorDiv'); // bind 'myForm' and provide a simple callback function var options = { //target: '#output1', // target element(s) to be updated with server response beforeSubmit : validate,// pre-submit callback dataType : 'json',// 'xml', 'script', or 'json' (expected server response type) //dataType必须放在callback(json)前面,因为callback(json)要调用json这个变量 success : function(json) { json = eval(json); if (json.errcode == 0) { window.location.href = 'seller/seller.jsp'; } else { error.innerHTML = "账号和密码错误,请重新登录."; } } // post-submit callback // other available options: //url: url // override for form's 'action' attribute //type: type // 'get' or 'post', override for form's 'method' attribute //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 }; $('#loginForm').ajaxForm(options); }); function validate() { var username = document.getElementById("name").value; var password = document.getElementById("pwd").value; //检测是否为空可以将其交给前台处理; if (username.length == 0) { error.innerHTML = "账号不能为空"; return false; } else if (password.length == 0) { error.innerHTML = "密码不能为空"; return false; } error.innerHTML = "正在登录"; } </script>
2、$.ajax
请求结果是json数据:response的json
$.ajax({ url : url, type : 'post', dataType : 'json', success : function(json) { json = eval(json); var obj = json.object; for ( var o in obj) { sel_type.options.add(new Option(obj[o].name, obj[o].id)); } } });
Response.class
private int errcode;
private String errmsg; private Object object;
Done