<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>login test</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="ajax方式"> <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script> <script type="text/javascript"> function login() { $.ajax({ // Several parameters need to pay attention to type: " POST " , // method type dataType: " json " , // expected data type returned by the server url: " /users/login " , // url data: $( ' # form1 ' ).serialize(), success: function (result) { console.log(result); // Print the data returned by the server (for debugging) if (result.resultCode == 200 ) { alert("SUCCESS"); } ; }, error : function() { alert( " Exception! " ); } }); } </script> </head> <body> <div id="form-div"> <form id="form1" onsubmit="return false" action="##" method="post"> <p>用户名:<input name="userName" type="text" id="txtUserName" tabindex="1" size="15" value=""/></p> <p>密 码:<input name="password" type="password" id="TextBox2" tabindex="2" size="16" value=""/></p> <p><input type="button" value="登录" onclick="login()"> <input type="reset" value="重置"></p> </form> </div> </body> </html>
Precautions
- In the common method, the type of the clicked login button is "submit";
- In the common way, the action of the form is not empty;
- What should be paid attention to in the ajax method is the parameters in the $.ajax method: dataType and data.
I seldom write front-end code, the level is the entry level, I can understand and change it, so it is often Baidu, like this time, the realization of this function is also with the help of Baidu, but the code I got from Baidu is in $. The value of the dataType parameter set in the ajax method is "html" instead of "json", which caused me to keep reporting errors when I started debugging, and finally changed to "json" to succeed, so here is a special explanation and reminder, don't Like me, I went the wrong way, and there is the data value transmitted to the server. Like the above code, the data in the form can be serialized and transmitted.