前后台传递参数

来源:互联网 发布:网络电视装机必备 编辑:程序博客网 时间:2024/05/01 02:46

前台传到后台

  1. 序列化表单
$("#goodsBuyForm").serialize();//字符串$("#goodsBuyForm").serializeObject();//json对象

将表单序列化为
name1=value1&name2=value2 的形式
用在ajax请求中

params = $("#goodsBuyForm").serialize();$.ajax({data:param,//data:{"params":params,"goodsSku":goodSkuId}// 这样想多传几个参数亲测不行,传到后台的参数也无法直接映射到对象中去})

serializeObject()基于JQuery的serializeArray()

/** * 将表单元素序列化为JSON对象 基于jQuery serializeArray() */$.fn.serializeObject = function() {    var o = {};    var a = this.serializeArray();    $.each(a, function() {        if (o[this.name] !== undefined) {//刚出现的表单name的值。为undefined直接保存name和value            if (!o[this.name].push) {//有相同name属性的表单,用数组保存                o[this.name] = [ o[this.name] ];            }            o[this.name].push(this.value || '');        } else {            o[this.name] = this.value || '';        }    });    return o;};

表单序列化为数组:数组的内容为{}json对象,json对象有两个键name和value
serializeArray不会序列化不需要提交的表单控件,跟常规的表单提交行为是一致的。不在<form>标签内的表单控件不会被提交、没有name属性的表单控件不会被提交、带有disabled属性的表单控件不会被提交、没有被选中的表单控件不会被提交。
参考博客
serializeObject()的功能更强大

后台传到前台。

方式1:
@ReponseBody 注解
返回的string,integer或者map类型直接传到页面,通常用于ajax请求在success:function(data)中用到后台返回的数据中。
应该是被这个注解过,就不会调用视图解析器了吧。
如果是返回要转向的页面就不能用这个注解了。

//data.count 取值    /**     * 获取购物车数量     * @param request     * @return     */    @RequestMapping("/getCartCount")    @ResponseBody    public int getCartCount(HttpServletRequest request){        try{            MemberInfo info = (MemberInfo) request.getAttribute("consumerInfo");            info = new MemberInfo();            info.setMemberId("100007377612");//测试代码            if(null == info) {                return 0;            }else{                int count = userGoodsCarService.count(info.getMemberId());                return count;            }        }        catch (Exception e){            return 0;        }    }

方式2:
要返回的值以键值对的形式存入model对象中

@RequestMapping("/linkToCartList")    public String linkToCartList(HttpServletRequest request,Model model){    model.addAttribute("shopSet", shopSet);            model.addAttribute("userGoodsCarList", userGoodsCarList);            model.addAttribute("skuIds", StringUtils.join(skuIds,";"));            model.addAttribute("cartGoodsNum", cartGoodsNum);    return "web/goods/cart/cartList";//交给视图解析器    }

方式3:
传JSONObejct对象的toString()方法。

JSONObject result = new JSONObject();result.put("status", 0);result.put("goodsWater", goodsWater);result.put("shopGoodsPrice", shopGoodsPrice);response.getWriter().write(result.toString());
gx工程:var valueData = eval("(" + data.responseText + ")");hn:success: function (data) {var goodsWater = data.goodsWater;var marketInfo = data.marketInfo;//没有使用eval将json字符串转化为json对象,应该是得不到数据的啊。好奇怪啊。

是因为:

dataType:"json";//将传过来的json型字符串转化为json对象//等价为eval("("+jsonString+")")的作用

这里写图片描述
json和javascript数组的转换