1. 程式人生 > >[JQ權威指南]表單外掛form

[JQ權威指南]表單外掛form

(1)功能描述:
在頁面中建立一個ID為”frmUserInfo”的表單,在表單中新建一個文字框,用於輸入使用者名稱。新建一個口令文字框,用於輸入密碼,單擊提交後,將向伺服器檔案login.aspx傳送請求。提交表單中的各元素值,伺服器響應請求,將返回的內容顯示在ID為”divData”頁面元素中。
(2)實現程式碼:
html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns
="http://www.w3.org/1999/xhtml">
<head> <title>form 表單外掛</title> <script src="Jscript/jquery-1.4.2.min.js" type="text/javascript"></script> <script src="Jscript/jquery.form.js" type="text/javascript"></script> <script type="text/javascript" > $(function
() {
//定義一個表單提交時的物件 var options = { //預設為form中的action,設定後便覆蓋預設值 url: "Login.aspx", //將伺服器返回的資料顯示在ID號為divData的元素中。 target: "#divData" } //以ajax的方式提交表單 $("#frmUserInfo").ajaxForm(options); })
</script> <style type="text/css"> body{font-size:13px} .divFrame{width:225px;border:solid 1px #666} .divFrame .divTitle{padding:5px;background-color:#eee;height:30px} .divFrame .divTitle span{float:left;padding:2px;padding-top:5px} .divFrame .divContent{padding:8px} .divFrame .divContent .clsShow{font-size:14px} .txt{border:#666 1px solid;padding:2px;width:150px;margin-right:3px} .btn {border:#666 1px solid;padding:2px;width:65px; </style> </head> <body> <form id="frmUserInfo" method="get" action="#"> <div class="divFrame"> <div class="divTitle"> 使用者登入 </div> <div class="divContent"> <div> 使用者名稱:<br /> <input id="username" name="username" type="text" class="txt" /> </div> <div> 密碼:<br /> <input id="userpass" name="userpass" type="password" class="txt" /> </div> </div> <div class="divBtn"> <input id="sbtUser" type="submit" value="提交" class="btn" /> </div> <div id="divData"></div> </div> </form> </body> </html>

伺服器端檔案:Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Ch8_Login"  ResponseEncoding="gb2312"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
     <% string strName = Request["username"];
        string strPass = Request["userpass"];
        string strRetValue = "使用者名稱:" + strName + "<br>密碼:" + strPass;
        Response.Write(strRetValue);

         %>

    </form>
</body>
</html>

(3)程式碼分析
在匯入form表單外掛之後,提交資料變得十分輕鬆,一行程式碼:
(“#frmUserInfo”).ajaxForm(options);  
    等於
(“#frmUserInfo”).submit.(function(){
$(“#frmUserInfo”).ajaxSubmit();
return false;
})