[color=blue]/**
* json前后台交互操作
*/[/color]
[color=red]/*
* A:
* 前台传入字符串参数
* 后台返回json字符串、或是json数组
*/[/color]
[color=red]/**
* B: 前台传入json数组作为参数与后台进行交互
* 后台返回数组、字符串
*/[/color]
* json前后台交互操作
*/[/color]
[color=red]/*
* A:
* 前台传入字符串参数
* 后台返回json字符串、或是json数组
*/[/color]
//前台js中
$.ajax({
url: "xxx/xxx.action",
data: "id=xxx",
cache: false,
async: false,
success: function(result)
{
A:接收后台返回的数组
var data = eval(result);
if (typeof(data) != "undefined" && data.length > 0)
{
for(var i=0;i<data.length;i++)
{
data[i]["id"];
data[i]["name"];
}
}
B: 后台返回字符串、则直接接收
},
error: function(){
alert("table loading error...");
}
});
PrintWriter out = ServletActionContext.getResponse().getWriter();
/*
* 后台返回json字符串
*/
StringBuffer string = new StringBuffer();
string.append("");
out.print(string);
/*
* 后台返回json数组
*/
List<String> list = new ArrayList<String>();
JSONArray jArray = JSONArray.fromObject(list);
out.print(jArray);
out.flush();
return null;
[color=red]/**
* B: 前台传入json数组作为参数与后台进行交互
* 后台返回数组、字符串
*/[/color]
/**
* 前台
*/
function delCheckedData(){
var array = new Array();
$(":checkbox[name='chk'][checked=true]").each(function(){
array.push({
id: $(this).val()
});
})
if (array.length > 0) {
var gridJSON = JSON.stringify(array, function(key, value){
return value;
});
$.ajax({
url: "/xxx/xxx.action",
cache: false,
data: "idListJSON=" + gridJSON,
async: false,
success: function(result){
var instData = eval(result);
//相应的处理
},
error: function(){
alert("Error...");
}
});
}
}
/*
* 后台接收前台的json数组并做处理
*/
JSONArray instArray = JSONArray.fromObject("参数");
for (int i = 0; i < instArray.size(); i++)
{
JSONObject instJ = (JSONObject)instArray.get(i);
String sId = instJ.get("id").toString();
//得到Id做相应的操作
}