jQuery梳理之Ajax

前言

本文內容摘自《jQuery中文網》,對ajax的一些函數做梳理

正文

比較常用的函數

jQuery.ajax()

它的data類型: Object,
String,如果contentType的類型是application/x-www-form-urlencoded;charset=utf-8,那麼可以用param(),serialize()
將對象、表單序列化成key-value pair
的字符串,賦給data,也可以直接將對象字面量給予data。如果是contentType是application/json,那麼需要用JSON.stringfiy,將對象字面量轉成json字符串,傳到後臺

jQuery.get()

例子

        /**  ajax get請求*/
        function ajaxGet() {
            $.get(basePath+"/ajaxGetDemo/45.do",
                    {userName:'demo',habit:'yes'},
                    function(data) {
                        alert(data.success);
                    },
           'json');
        }

後臺

@RequestMapping(value="ajaxGetDemo/{index}",method=RequestMethod.GET)
    @ResponseBody
    public Map<String,Object> ajaxGet(@PathVariable Integer index,DemoCond cond) throws Exception {
        Map<String,Object> results = new HashMap<String,Object>();
        results.put("success", true);
        return results ;
    }

headers
RequestURL:http://localhost:8080/perfect/ajaxGetDemo/45.do?userName=demo&habit=yes
Request Method:GET

jQuery.post()

jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

例子

        /**  ajax post請求*/
        function ajaxPost() {
            $.post(basePath+"/ajaxGetDemo/45.do",
                    {userName:'demo',habit:'yes'},
                    function(data) {
                        alert(data.success);
                    },
           'json');
        }

後臺

    @RequestMapping(value="ajaxGetDemo/{index}")
    @ResponseBody
    public Map<String,Object> ajaxGetAndPost(@PathVariable Integer index,DemoCond cond) throws Exception {
        Map<String,Object> results = new HashMap<String,Object>();
        results.put("success", true);
        return results ;
    }

headers
Request URL:http://localhost:8080/perfect/ajaxGetDemo/45.do
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
userName=demo&habit=yes

一些簡單的例子

application/x-www-form-urlencoded

/** 使用ajax默認的表單提交,application/x-www-form-urlencoded*/
        function handleUseForm() {
            var text = $("form").serialize();  //key=value  & key = value的形式
            $.ajax({
                url :  basePath+"/demo.do",
                type : "post",
                data : text,
                success : function(result) {
                    alert(result.success);
                }
            });
        }

後臺

    @RequestMapping(value="demo")
    @ResponseBody
    public Map<String,Object> saveDemoByForm(DemoCond cond) throws Exception {
        Map<String,Object> results = new HashMap<String,Object>();
        Demo demo = new Demo();
        BeanUtils.copyProperties(demo, cond);
        demoServiceImpl.saveDemo(demo);
        results.put("success", true);
        return results ;
    }

headers
Request URL:http://localhost:8080/perfect/demo.do
Request Method:POST
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
userName=nice&habit=1&sex=1&job=android&job=ios

application/json

        /** 使用ajax contentType:application/json上傳*/
        function handleUseJson() {
            var params = $("form").serializeObject();
            $.ajax({
                url :  basePath+"/demo4json.do",
                dataType:"json",
                contentType: "application/json; charset=utf-8",
                type : "post",
                data : JSON.stringify(params),
                success : function(result) {
                    alert(result.success);
                }
            });
        }

後臺

    @RequestMapping(value="demo4json")
    @ResponseBody
    public Map<String,Object> saveDemoByJson(@RequestBody DemoCond cond) throws Exception {
        Map<String,Object> results = new HashMap<String,Object>();
        Demo demo = new Demo();
        BeanUtils.copyProperties(demo, cond);
        demoServiceImpl.saveDemo(demo);
        results.put("success", true);
        return results ;
    }

headers
Request URL:http://localhost:8080/perfect/demo4json.do
Request Method:POST
Content-Type:application/json; charset=UTF-8
{“userName”:”nice”,”habit”:”1”,”sex”:”1”,”job”:[“android”,”ios”]}

serializeObject

$.fn.serializeObject = function(){
            var option = {};
            var array = this.serializeArray();
            $.each(array, function() {
                if (option[this.name] !== undefined) {
                    if (!option[this.name].push) {
                        option[this.name] = [option[this.name]];
                    }
                    option[this.name].push(this.value || '');
                } else {
                    option[this.name] = this.value || '';
                }
            });
            return option;
        }
jQuery.form.js插件

ajaxForm

Prepares a form to be submitted via AJAX by adding all of the
necessary event listeners. It does not submit the form. Use ajaxForm
in your document’s ready function to prepare your form(s) for AJAX
submission. ajaxForm takes zero or one argument. The single argument
can be either a callback function or an Options Object.

這個函數,綁定了自定義的submit的事件,一旦我們觸發了submit就會請求後臺

例子

<body>
    <form id="myForm">
        Name: <input type="text" name="userName" /> Comment:
        <textarea name="habit"></textarea>
        <input
            type="checkbox" name="job" value="android" /> ios <input
            type="checkbox" name="job" value="ios" />
        <input type="submit" />點擊
    </form>
    <script>
       $(function(){
           $('#myForm').ajaxForm({
                type: 'post',
                dataType: 'json',
                data:{sex: 0},
                url: basePath +'/jQueryFormPlugin.do',
                beforeSubmit: function(formData, jqForm, options) {
                    //可以做一些表單的校驗
                var queryString = $.param(formData);
                        alert('About to submit: \n\n' + queryString);
                },
                success: function(data) {
                    alert(data.msg);
                }
                });
       })
    </script>
</body>

點擊submit就可以觸發發送請求
headers
Request URL:http://localhost:8080/perfect/jQueryFormPlugin.do
Request Method:POST
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
userName=nice&habit=code&job=android&job=ios&sex=0

ajaxSubmit

mmediately submits the form via AJAX. In the most common use case this is invoked in response to the user clicking a submit button on the form. ajaxSubmit takes zero or one argument. The single argument can be either a callback function or an Options Object.

不需要限制於submit,這也是兩者的區別,ajaxForm內部調用ajaxSubmit

// prepare the form when the DOM is ready
$(document).ready(function() {
    var options = {
        target:        '#output2',   // target element(s) to be updated with server response
        beforeSubmit:  showRequest,  // pre-submit callback
        success:       showResponse  // 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
    };

    // bind to the form's submit event
    $('#myForm2').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 !!!  需要設置false,否則ajaxSubmit請求一次,submit又請求一次,可以使用event.preventDefault().
        // always return false to prevent standard browser submit and page navigation
        return false;
    });
});

// pre-submit callback
function showRequest(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: \n\n' + 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;
}

// post-submit callback
function showResponse(responseText, statusText, xhr, $form)  {
    // for normal html responses, the first argument to the success callback
    // is the XMLHttpRequest object's responseText property

    // if the ajaxSubmit method was passed an Options Object with the dataType
    // property set to 'xml' then the first argument to the success callback
    // is the XMLHttpRequest object's responseXML property

    // if the ajaxSubmit method was passed an Options Object with the dataType
    // property set to 'json' then the first argument to the success callback
    // is the json data object returned by the server

    alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
        '\n\nThe output div should have already been updated with the responseText.');
}

結束語

  1. ajax默認contentType的類型是application/x-www-form-urlencoded;charset=utf-8
    這個類型,在springmvc框架中,可以根據key-value pair來自動映射到參數對象中
  2. ajax的contentType的類型是application/json,那麼在springmvc框架中需要增加註解:@RequestBody,json字符串可以用jackson解析成所接收的對象
  3. ajax提交可以在路徑後面跟上動態變量,來代替之前的url?key=value&key=value
    這種形式的傳值,在springmvc框架中,需要註解@PathVariable,並且接收的路徑包含{}
發佈了88 篇原創文章 · 獲贊 29 · 訪問量 29萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章