Jquery ajax的常用方法 前后端

来源:互联网 发布:indesign mac 编辑:程序博客网 时间:2024/05/20 23:30

Ajax常用参数

<script type = "text/javascript">$.ajax({    type: 'GET', // 这是请求的方式 可以是GET方式也可以是POST方式, 默认是GET    url: ' xxx.php ', // 这是请求的连接地址 一般情况下这个地址是后台给前端的一个连接,直接写就可以    dataType: 'json', //预期后端返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断    async: true, // 默认为true,默认为true时,所有请求均为异步请求,如果需要发送同步请求,需设置为false,    timeout: 8000, // 设置请求超时时间(毫秒)。此设置将覆盖全局设置    data: {        // 要传递的参数        'xxx': 'xxx',        ......    },    beforeSend: function(XHR) {        // 在发送请求前就开始执行 (一般用来显示loading图)    },    success: function(data) {        // 发送请求成功后开始执行,data是请求成功后,返回的数据    },    complete: function(XHR, TS) {        //当请求完成后开始执行,无论成功或是失败都会执行 (一般用来隐藏loading图)    },    error: function(xhr, textStatus, errorThrown) {        //  请求失败后就开始执行,请求超时后,在这里执行请求超时后要执行的函数    }}).done(function() {    // 这个函数是在ajax数据加载完之后,对数据进行的判断,在涉及到对ajax数据进行操作无效时,在这个函数里面写是可以起到效果的   });</script>

$.ajax 示例:

<script type="text/javascript">    //验证码验证    function checkPicCode() {        var code = $("#inputCode").attr("value");        code = "c=" + code;        $.ajax( {            type : "post", //GET / POST ,这个参数默认值 GET            url : "/index/Servlet",            data : code,    //后台获取parameter("c");            dataType: 'json',            success : callback        });    }    //验证以后处理提交信息或错误信息    function callback(data) { }</script>

$.getJSON

<script type="text/javascript>/*--$.getJSON(url,function) 中的function是在$.getJSON请求成功后回调的。如果请求失败是不会调用的。--*/    $.getJSON("http://域名/请求路径", function(返回的json数据){解析json数据 或者  调用其他方法(返回的json数据);});</script>

$.ajax jsonp请求

<script type = "text/javascript">    $.ajax({        url: 'http://localhost:8080/jsonpTest', //请求的url        dataType: "jsonp", //要求后端返回的数据类型。如果不指定,jQuery 将自动根据 HTTP 包 MIME 信息来智能判断        jsonp: "jsonpCallbackParam", //传递给后端的参数名,服务端会通过这个参数拿到回调函数名称callbackMethodName        jsonpCallback: "callbackMethodName", //自定义的jsonp回调函数名称,返回 函数名称(json数据)        success: function(data) {        // 发送请求成功后开始执行,data是请求成功后,返回的数据        },        error: function(xhr, status, error) { console.log(xhr); }    });    ////自定义的jsonp回调函数, 先于success方法执行    function callbackMethodName(data){}</script>

$.ajax jsonp请求 示例

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title>jsonp test Page</title>        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>        <script type="text/javascript">            jQuery(document).ready(function() {                $.ajax({                    type: "get",                    async: true,                    url: "http://localhost:8080/jsonpTest",                    //data: {name:"hao123",age:17},                    dataType: "jsonp",      //要求 服务端返回的数据类型                    jsonp: "callbackparam", //传递给服务端,用以获得jsonp回调函数名的参数名(默认为:callback)                    jsonpCallback: "callbackMethodName", //自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名                    success: function(data) {                        alert("successMethod==="+data.msg);                    },                    error: function() {                        alert('fail!');                    }                });            });            //自定义的jsonp回调函数, 先于success方法执行            function callbackMethodName(data){                alert("callbackMethod==="+data.msg);            }            /*//服务端spring mvc controller 的测试方法可返回json数据/jsonp数据。            // produces=MediaType.APPLICATION_JSON_VALUE+";charset=utf-8"            @RequestMapping(value = "/jsonpTest", method = RequestMethod.GET ,produces="application/json; charset=utf-8")            @ResponseBody            public String testJsonp(@RequestParam("callbackparam") String callbackparam) {                if(callbackparam.isEmpty()){ // 为空,返回json                    return "{msg:\"server response  message.\"}";                }                // 不为空,返回jsonp                return callbackparam+"({msg:\"server response  message.\"})";            }*/        </script>    </head>    <body>    </body></html>

$.getJSONP

<script type="text/javascript">    /*base.js*/    !function($) {        $.extend({_jsonp: {scripts: {},counter: 1,charset: "UTF-8",head: document.getElementsByTagName("head")[0],name: function(callback) {                    var name = "_jsonp_" + (new Date).getTime() + "_" + this.counter;                    this.counter++;                    var cb = function(json) {                        eval("delete " + name), callback(json), $._jsonp.head.removeChild($._jsonp.scripts[name]), delete $._jsonp.scripts[name]                    };                    return eval(name + " = cb"), name                },load: function(a, b) {                    var c = document.createElement("script");                    c.type = "text/javascript", c.charset = this.charset, c.src = a, this.head.appendChild(c), this.scripts[b] = c                }},              getJSONP: function(a, b) {                var c = $._jsonp.name(b), a = a.replace(/{callback};/, c);                return $._jsonp.load(a, c), this              }})    }(jQuery);</script><script type = "text/javascript">/*------$.getJSONP----------------------*/    $.getJSONP("http://域名/请求路径?callback=resultMethod");    /*服务器返回的内容 resultMethod({"k":"v","k":"v","k":[...]})     相当于在这个位置写了一句调用下面方法的js代码*/    function resultMethod(json){解析json数据}</script>

$.getJSONP 示例

<!DOCTYPE html><html>    <head>        <meta charset="UTF-8">        <title>jsonp test Page</title>        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>        <script type="text/javascript">            //base.js 定义一个全局的$.getJSONP方法            ! function($) {                $.extend({                    _jsonp: {                        scripts: {},                        counter: 1,                        charset: "UTF-8",                        head: document.getElementsByTagName("head")[0],                        name: function(callback) {                            var name = "_jsonp_" + (new Date).getTime() + "_" + this.counter;                            this.counter++;                            var cb = function(json) {                                eval("delete " + name), callback(json), $._jsonp.head.removeChild($._jsonp.scripts[name]), delete $._jsonp.scripts[name]                            };                            return eval(name + " = cb"), name                        },                        load: function(a, b) {                            var c = document.createElement("script");                            c.type = "text/javascript", c.charset = this.charset, c.src = a, this.head.appendChild(c), this.scripts[b] = c                        }                    },                    getJSONP: function(a, b) {                        var c = $._jsonp.name(b),                            a = a.replace(/{callback};/, c);                        return $._jsonp.load(a, c), this                    }                })            }(jQuery);            $(function(){                //使用方法                // $.getJSONP("http://域名/请求路径?callback=回调方法名");                $.getJSONP("http://localhost:8080/jsonpTest?callback=resultMethod");            });            //回调方法            function resultMethod(data) {                alert(data.msg)            }            /*//服务端spring mvc controller 的测试方法,可返回json数据/jsonp数据。            @RequestMapping(value = "/jsonpTest", method = RequestMethod.GET ,produces="application/json; charset=utf-8")            @ResponseBody            public String testJsonp(@RequestParam("callback") String callbackparam) {                if(callbackparam.isEmpty()){ // 为空,返回json                    return "{msg:\"server response  message.\"}";                }                // 不为空,返回jsonp                return callbackparam+"({msg:\"server response  message.\"})";            }            //服务端返回数据  resultMethod({msg:"server response  message."})*/        </script>    </head>    <body>    </body></html>

服务端第二种方法写法

    //使用 MappingJacksonValue ,要求springmvc必须是4.1以上版本。        @RequestMapping(value="/jsonpTest" )        @ResponseBody        public Object testJsonp(String callbackparam) {            String result = new User(1212,"orz"); //Java对象            if(callbackparam.isEmpty()){ // 为空,返回json                return result;            }            //不为空,需要支持jsonp调用            MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(result);            mappingJacksonValue.setJsonpFunction(callbackparam);            return mappingJacksonValue;        }
原创粉丝点击