当前位置: 代码迷 >> Ajax >> java中怎么在ajax发送参数的时候,参数以数组的方式传递到后数组台
  详细解决方案

java中怎么在ajax发送参数的时候,参数以数组的方式传递到后数组台

热度:708   发布时间:2012-07-24 17:47:58.0
java中如何在ajax发送参数的时候,参数以数组的方式传递到后数组台

/*配对后发送微博,这个需要@xx*/
??? function faweibo(id){
??? ??? var users = new Array();
??? ?
??? ??? $("#friendList dd p input[type=checkbox]").each(function(i){
??? ??? ??? if($(this).attr("checked"))
??? ??? ??? ??? users.push(encodeURIComponent($(this).val()));
??? ??? });
??? ???
??? ??? users = toJSON(users);
??? ??? $.ajax({
??? ??? ??? ??? ?? type:'post',
??? ??? ??? ??? ?? url:"/qq/pei/faweibo.do",
??? ??? ??? ??? ?? data:{'users':users},
??? ??? ??? ??? ?? success: function(data){
??? ??? ??? ???
??? ??? ??? ??? ?? popfruit('send_ok',200);
??? ??? ??? });
??? }

?

上面的这个函数是当弹窗一个窗口的时候,获取用户选择的checkbox,如果选中了就将用户的id放到数组,传给后台

这里需要一个arraytoson的方法

//将一个数组转换json对象
??? function toJSON(obj){
??? ??? ?var json = '({';
??? ??? $.each(obj, function(k,v){
??? ??? ? var q = typeof v == 'string' ? ~v.indexOf("'") ? '"' : "'" : '';
??? ??? ? if (typeof v == 'object')
??? ??? ???? v = toJSON(v).slice(0,-1).substr(1);
??? ??? ? json+= k + ':'+ q + v + q + ',';
??? ??? });
??? ??? ?return json.slice(0,-1)+'})';
??? ??? };

?

如果后台是用php就简单多了,? data:{'users':users},根本就不要转换。在java中就需要自己进行转换。

下面的parseJsonToArray就是负责转换的。

?

?

@Action(value = "faweibo", results = { @Result(name = SUCCESS, type = "json", params = {
??? ??? ??? "target", "jsonMap" }) })
??? public String faweibo() throws Exception {
??? ??? String users = request.getParameter("users");

??????? users = java.net.URLDecoder.decode(users, "utf-8");
??? ??? List<String> u = parseJsonToArray(users);

?????? //u中放的就是前台传过来的userId的值。

?

}

?

这里需要解析传过来的json字符串

?

public static List<String> parseJsonToArray(String data) {
??? ??? List<String> list = new ArrayList<String>();
??? ??? if (null == data || data.length() == 0) {
??? ??? ??? return null;
??? ??? }
??? ??? if (data.length() < 4) {
??? ??? ??? return null;
??? ??? }
??? ??? String temp = data.substring(2, data.length() - 2);
??? ??? temp = temp.replaceAll("\\'", "");
??? ??? String splitResult[] = temp.split(",");
??? ??? for (int i = 0; i < splitResult.length; i++) {
??? ??? ??? list.add(splitResult[i].substring(splitResult[i].indexOf(":") + 1));
??? ??? }
??? ??? return list;
??? }

这样就可以获得前台传过来的多个参数。

?

这里想要要用数组来传参,而不是通过 data:{'user1':user1,''user2':user2,''user3':user3,'}这样的方式,主要是考虑如果有多个checkbox的时候,这样添加参数会很蛋疼。所以想到用数组传参来解决这个问题。

?

以上是自己在项目中用的解决办法,希望可以得到大家的指点。

?

  相关解决方案