zoukankan      html  css  js  c++  java
  • 前端开发

    1.使用ajax传递对象

    前端代码:

    function save(status) {
        var dataList = $table.bootstrapTable("getData", true);
        var obj = dataList[0];
        obj.status = status;
        obj.opinion = $("#opinion").val();
    
        $.ajax({
            type: "post",
            url: "/admin/warning/approve/save",
            contentType: 'application/json;charset=utf-8',
            data: JSON.stringify(obj),
            dataType: "json",
            success: function (msg) {
                console.log(msg);
                if (msg.code == 0) {
                    layer.msg(msg.message, {icon: 1, time: 1000}, function () {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    });
                } else {
                    layer.msg(msg.message, {icon: 2, time: 1000})
                }
            }
        });
    }
    

    后端代码:

    /**
     * 保存
     * @param costStr
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public JsonResult save(@RequestBody String costStr){
        CostApplication costApplication = JSON.parseObject(costStr, new TypeReference<CostApplication>() {});
        costApplicationService.save(costApplication);
        return JsonResult.success();
    }
    

    2.使用post方式传递多个参数

    前端代码:

    function saveOrSubmit(type) {
        var dataList = $table.bootstrapTable("getData", true);
        console.log(dataList);
        console.log($("#kj").val());
        $.ajax({
            type: "post",
            url: "/admin/warning/apply/save",
            data: {
                saveType: type,
                dataListStr: JSON.stringify(dataList),
                bzy: $("#bzy").val(),
                kj: $("#kj").val(),
                cn: $("#cn").val(),
            },
            dataType: "json",
            success: function (msg) {
                // msg = JSON.parse(msg);
                console.log(msg);
                if (msg.code == 0) {
                    layer.msg(msg.message, {icon: 1, time: 2000}, function () {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index);
                    });
                } else {
                    layer.msg(msg.message, {icon: 2, time: 2000})
                }
            }
    
        });
    }
    

    后端代码:

    /**
     * 保存
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public JsonResult save(Integer saveType, String dataListStr, String reason, String bzy, String kj, String cn, HttpSession session, ModelMap map){
        List<CostApplication> dataList = readListValue(dataListStr, CostApplication.class);
        if (dataList != null){
            for (CostApplication c: dataList){
                if (saveType != null){
                    c.setStatus(saveType);
                }
                if (reason != null){
                    c.setReason(reason);
                }
                if (bzy != null){
                    c.setBzy(bzy);
                }
                if (kj != null){
                    c.setKj(kj);
                }
                if (cn != null){
                    c.setCn(cn);
                }
            }
            costApplicationService.save(dataList);
            return JsonResult.success();
        }
        return JsonResult.failure("操作失败!");
    }
    

    同步与异步

    ajax的async这个属性默认是true:异步,false:同步。

    使用示例:

     $.ajax({
            type: "GET",
            dataType: 'json',
            async: false,
            contentType: 'application/json;charset=utf-8',
            url: ctx+"/admin/cashierManager/getCode",
            success: function(msg){
                if (msg.code === 0){
                    console.log(msg.data);
                }
            }
        });
    

    这个属性可以相对的减少代码运行书序问题,但是如果用的太多,页面假死次数太多。这样反而导致用户体验不佳~!

    $.Ajax()中 async 和success的官方的解释:

    async 
    Boolean 
    Default: true
    
    By default, all requests are sent asynchronous (e.g. this is set to true by default). 
    If you need synchronous requests, set this option to false. Note that synchronous 
    requests may temporarily lock the browser, disabling any actions while the request 
    is active.
    
    success 
    Function
    
    A function to be called if the request succeeds. The function gets passed two 
    arguments: The data returned from the server, formatted according to the 'dataType'
    parameter, and a string describing the status. This is an Ajax Event.
    

    在这里,async默认的设置值为true,这种情况为异步方式,就是说当ajax发送请求后,在等待server端返回的这个过程中,前台会继续 执行ajax块后面的脚本,直到server端返回正确的结果才会去执行success,也就是说这时候执行的是两个线程,ajax块发出请求后一个线程 和ajax块后面的脚本(另一个线程)例:

    $.ajax({  
        type:"POST", 
        url:"Venue.aspx?act=init", 
        dataType:"html", 
        success:function(result){   //function1()
            f1(); 
            f2(); 
        } 
        failure:function (result) {  
            alert('Failed');  
        }, 
    } 
    function2(); 
    

    在上例中,当ajax块发出请求后,他将停留function1(),等待server端的返回,但同时(在这个等待过程中),
    前台会去执行function2(),也就是说,在这个时候出现两个线程,我们这里暂且说为function1() 和function2()。

    当把asyn设为false时,这时ajax的请求时同步的,也就是说,这个时候ajax块发出请求后,他会等待在function1()这个地方,
    不会去执行function2(),直到function1()部分执行完毕。

    $.ajax()方法常用参数详解

    $.ajax()方法是jQuery最底层的Ajax实现。它的结构为:
    
      $.ajax(options)
    
    该方法只有一个参数,但是这个对象里包含了$.ajax()方法所需要的请求设置以及回调函数等信息,参数以key/value的形式存在,所有的参数都是可选的。
    常用参数见下表:
    
    1.url
    
    要求为String类型的参数,(默认为当前地址)发送请求的页面。
    
    2.type
    
    要求为String类型的参数,请求方式(post或get)默认为get。注意其他http请求方法,例如put和delete也可以使用,但仅部分浏览器支持。
    
    3.data
    
    要求为Object或String类型的参数,发送到服务器的数据。如果不是字符串,将自动转换为字符串格式。get请求中将附加在URL后。防止这种自动转换,可以查看  
    processData选项。对象必须为key/value格式,例如{foo1:"bar1",foo2:"bar2"}转换为&foo1=bar1&foo2=bar2。
    如果是数组,JQuery将自动为不同值对应同一个名称。例如{foo:["bar1","bar2"]}转换为&foo=bar1&foo=bar2。
    
    4.contentType
    
    要求为String类型的参数,当发送信息至服务器时。内容编码类型默认为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。
    
    5.dataType
    
    要求为String类型的参数,预期服务器返回的数据类型。如果不指定,jQuery将自动根据HTTP包的mine信息返回responseXML或responseText,
    并作为回调函数参数传递。可用的类型如下:
    
      xml:返回XML文档,可用jQuery处理。
    
      html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
    
      script:返回纯文本javascript代码。不会自动缓存结果,除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。
    
      json:返回JSON数据。
    
      jsonp:JSON格式。使用JSONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个“?”为正确的函数名,以执行回调函数。
    
      text:返回纯文本字符串。
    
    6.success
    
    要求为Function类型的参数,请求成功后调用的回调函数,有两个参数。
    
      (1)由服务器返回,并根据dataType参数进行处理后的数据。
    
      (2)描述状态的字符串。
    
      function(data,textStatus){
    
        //data可能是xmlDoc、jsonObj、html、text等
    
        this;    //调用本次ajax请求时传递的options参数
    
      }
    
    7.error
    
    要求为Function类型的参数,请求失败时被调用的函数。该函数有3个参数,即XMLHttpRequest对象、错误信息、捕获的错误对象(可选)。ajax事件函数如下:
    
      function(XMLHttpRequest,textStatus,errorThrown){
    
        //通常情况下textStatus和errorThrown只有其中一个包含信息
    
        this;    //调用本次ajax请求时传递的options参数
    
      }
    
    8.async
    
    要求为Boolean类型的参数,默认设置为true,所有请求均为异步请求。如果需要同步请求,请将此选项设置为false。
    注意,同步请求将锁住浏览器,用户其他操作必须等待请求完成才可以执行。
    

    参考

    https://www.cnblogs.com/xmphoenix/archive/2011/11/21/2257651.html

    https://www.cnblogs.com/lengyuehuahun/p/5626668.html

  • 相关阅读:
    Ⅲ:作业
    Ⅱ:python入门
    Auth模块
    django中间件
    Django的cookie以及session
    form组件
    Django Ajax
    Django模板层3和ajax初始
    聚合/分组 查询 事务
    Django ORM常用模块
  • 原文地址:https://www.cnblogs.com/zhangnianlei/p/12239257.html
Copyright © 2011-2022 走看看