局部刷新与json

通过这两天的探索,终于实现了网页的局部刷新和json的运用。话很少说,上码-.-html

 

后台封装将对象数据封装为json类型的数据:前端

json包org.json.jar包ajax

 

 

JSONObject jsonCup = new JSONObject();sql

list = gDao.queryGoods(sql);json

int i =0; 
for (Goods goods : list) { async


  JSONObject propertyJsont = new JSONObject();   //实例化JSONObj对象(属性)
  String id = goods.getGid();
  String name = goods.getGname();
  float price = goods.getGprice();
 //System.out.println(id + name + price);
  propertyJsont.put("id", id);            //将属性放入jsonCup对象
  propertyJsont.put("name", name);
  propertyJsont.put("price", price);
  jsonCup.put("goods" + i, propertyJsont); //将propertyJson放入jsonCup,一条键值对,表明一个商品数据
  i++;
}
out.println(jsonObject);post

 

前端ajax获取json数据:测试

$.ajax({网站

  type: "post",
  url: "/15301197_hejiaheng/selectGoodsAjaxTest",
  cache: false,
  async: true,
  dataType:"json",

  success: function(data){
    //alert(JSON.stringify(data)); //将data解析为字符串,能够查看data的数据
    var html = ""; //定义html字符串url

      for(var key in data){  //获得数据data,遍历
      var id = data[key]['id'];      //取出key值所对应的value值的id属性,这里有三个属性(id,name,price)
      var name = data[key]['name'];
      var price = data[key]['price'];
      html += "<p>编号:" + id + " 名称:" + name + " 价格:" + price + "</p>"; //拼接html字符
    }

  $("#goodsList").html(html); //html语句写入id = “goodsList ”的div中,即实现局部的数据加载。
},

  error: function(error){
    alert("获取信息失败!" + textStatus);
  }
});

 

这是一次性的局部刷新,还有按时的局部刷新,即计时器+这种方法能够实现。

通过测试后,我用它改进了之前小组作的一个网站做品上首页的快速查找功能,确实比全局刷新好多了。

相关文章
相关标签/搜索