java + jquery + ajax + json 交互
- 前端js格式:
- $.ajax({
- async:true,
- cache:false,
- type:"POST",
- dataType : 'json',
- url:"/shopping/cart/cartNum",
- error:function(json){alert(json);},
- timeout:60000,
- success:function(json){
- if(json.isSuc){
- $("#dscCartNum").html(json.datas);
- }else{
- $("#dscCartNum").html(json.des);
- }
- }
- });
$.ajax({ async:true, cache:false, type:"POST", dataType : 'json', url:"/shopping/cart/cartNum", error:function(json){alert(json);}, timeout:60000, success:function(json){ if(json.isSuc){ $("#dscCartNum").html(json.datas); }else{ $("#dscCartNum").html(json.des); } } });
- 后端(servlet)写法:
- try{
- response.setContentType("text/html;charset=utf-8");
- PrintWriter out = response.getWriter();
- out.write("{\"des\" : \""+des+"\" , \"isSuc\" : "+isSuc+" , \"datas\" : \""+dataStr+"\"}";);
- }catch(Exception ex){
- ex.printStackTrace();
- }