jQuery梳理之Ajax

来源:互联网 发布:cyc指标源码 编辑:程序博客网 时间:2024/05/22 07:03

前言

本文内容摘自《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 callbackfunction 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 callbackfunction 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,并且接收的路径包含{}
0 0
原创粉丝点击