1.前台页面ajax提交数据:
下面是批量删除的例子:
function deleteAudio(){ var audioNums = []; for (var i = 0; i < $("input[type=checkbox]:checked").length; i++) { audioNum = $("input[type=checkbox]:checked").eq(i).val(); audioNums[audioNums.length] = audioNum; }
//将数据转换为json数组提交 var jsonString = JSON.stringify(audioNums); $.ajax({ url : "operateAudio.shtml", type : "post", dataType : "json", data : {"audioNum" : jsonString,"method":"deleteAudio"}, success : function(data){ if(data.success == 1){ alert("删除数据成功"); location.reload(); } } }); }
2.后台servlet代码:
String audioJson = request.getParameter("audioNum"); //将得到的字符串转换为Json数组 JSONArray jsonArray = JSONArray.fromObject(audioJson); for (int i = 0; i < jsonArray.size(); i++) {
//jsonArray.getString(i)获得json数组的每一项 Date audioDate = dao.queryData(jsonArray.getString(i)); File file = new File("mp3/"+audioDate); if(file.exists()){ file.delete(); } } PrintWriter out = response.getWriter(); out.write("{\"success\":1}"); out.close();
JSONArray需要json-lib的jar包,一共6个分别是:
1)commons-beanutils-1.9.3.jar
2)commons-collections-3.2.jar
3)commons-lang-2.5.jar
4)commons-logging-1.2.jar
5)ezmorph-1.0.6.jar
6)json-lib-2.4-jdk15.jar
这6个包有版本问题,最好使用博主分享的这几个版本.