Jquery.Form非同期提出フォームの簡単な例


http://www.vaikan.com/docs/jquery.form.plugin/jquery.form.plugin.html#
1.あなたのページにフォームを書きます。一般的なフォームでは、特別なマークは必要ありません。

<form id="myForm" method="post" action="/Home/AjaxForm">
<div>
Name:<input id="username" name="username" type="text" /> &nbsp;
Password:<input id="password" name="password" type="text" />
<br />
<input type="submit" value="submit async" id="lnkSubmit" />
</div>
</form>
は、Jquery.Formコンポーネントがないときにフォームを提出し、ページがブロックモードになり、サーバー側の応答を待っています。
2.jQueryとForm Plugin Javascriptスクリプトファイルを導入し、いくつかの簡単なコードを追加してDOMロードが完了したらフォームを初期化する:
                にjquery.formのコンポーネントを追加した後、フォームを提出する時、ページは再び同期して提出するのではなく、jsから非同期で提出しますので、提出後のページは更新されません。
3.サーバ側と対話できるコールバック関数を追加します。

$(document).ready(function () {
     //options是一个ajaxForm的配置对象。?
     var options = {
        //target: '#output1',   // target element(s) to be updated with server response 
        //beforeSubmit: showRequest,  // pre-submit callback 
       <FONT color=#ff0000> success: callBackFunc  // post-submit callback</FONT> 

        // 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 form using 'ajaxForm' 
    $('#myForm').ajaxForm(options);
}); 

 // responseText是服务端的响应值。statusText是页面

 // 提交状态值,success表示成功。
function callBackFunc(responseText, statusText) {
    if (statusText == 'success') {
        alert(responseText);
    }

 else{

 alert(“服务端错误!”);

      }
}

如果返回的是json数据则回调函数可以这么写
function resultFunction(responseText,statusText) {
        if (statusText == 'success') {
            if (responseText.code == 1) {
                alert(responseText.message);
            } 
            else {
                alert('error occurs!');
            }
        }
        else {
            alert('服务器错误!');
        }
    }

サービスエンドのコードは以下の通りです。

[HttpPost]
public ActionResult AjaxForm(FormCollection form)
{
    string message = "Name:" + form["username"] + " PWD: "+form["password"]  ;
    //return Content(message);
    return Json(new { code = 1, message = message });
}
4.提出前のデータチェック関数に参加して、オプティクスオブジェクトにbeforSubmit属性を追加した

var options = {
                //target: '#output1',   // target element(s) to be updated with server response 
                <FONT color=#ff0000>beforeSubmit: checkData,  // pre-submit callback 
</FONT>                success: callBackFunc  // 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 
                //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 
            };
 // pre-submit callback 
       function checkData(formData, jqForm, options) {
           // formData is an array; here we use $.param to convert it to a string to display it 
           // but the form plugin does this for you automatically when it submits the data 
           //var queryString = $.param(formData);

           // jqForm is a jQuery object encapsulating the form element.  To access the 
           // DOM element for the form do this: 
           var formElement = jqForm[0]; 

           //alert('About to submit:

' + queryString);

           // here we could return false to prevent the form from being submitted; 
           // returning anything other than false will allow the form submit to continue 
           //return true;
           if ($(formElement).find("#username").val() == "") {
               alert("please enter username!");
               return false;
           } else {
               return true;
           }
       }
は、ユーザ名が空かどうかを検証し、入力を促すとともに、フォームの提出をキャンセルします。