jQuery使用JSON的例子

来源:互联网 发布:比价网源码 编辑:程序博客网 时间:2024/06/01 09:59

1、在HTML中,有这样一个表单:

  1. <form method="post" name="searchform" id="searchform" method="/sek.go"> 
  2. <input name="query" value="" type="text" id="query" /> 
  3. <input type=”submit” value="查询"></input> 
  4. </form> 

 

当然,要想在HTML中使用Js功能,必须在<head/>中加入

  1. <script type="text/javascript"src="/style/js/ajax.js"></script> 

 

2、然后在ajax.js文件中加入如下代码

  1. function userSearch(){  
  2.  
  3. var query = $("#searchform input[@name='query']").val();   
  4.  
  5.  
  6. $.post("/userSearch.htm", { query: query } ,function callback(json){  
  7.  
  8. var userlist = $.parseJSON(json);  
  9.  
  10. userList(userlist);  
  11.  
  12. });   
  13.  
  14. }  
  15.  

解释如下:

1)、"#searchform input[@name='query']";的意思是: 选择id为searchform其下的(name属性值为’query’的)input标签

2)、$(“”).val()意为要得到(“”)所选中属性的值;

3)、在$.post()中,第一项参数是指定目标servlet,即要把本post请求发给的那个servlet。

第二项是本post请求所携带的数据;“:”前的为key或者name,后为value;

第三项是回调函数,其内若有形参,则表示要对从servlet返回的值进行处理,这里的callback的功能是将JSON对象json转换成了JS对象userlist,然后将JS对象传入函数userList

3、post请求携带了名为query的参数去了后台,在servlet中进行处理:

  1. //从名为"query"能的参数中取出post带过来的数据  
  2. String query = request.getParameter("query");  
  3. if (query != null && !query.isEmpty()  
  4. && !query.trim().equalsIgnoreCase("")) {  
  5. //如果"query"的值不为空,就用'query'为参数构建HQL语句  
  6. String hql = "from TUser as user where user.userName like '"+ query + "%'";  
  7. //到库表TUser中进行查询,并得到一个表结构  
  8. List list = weilav3TUserDAO.getListByHQL(hql);  
  9. if (list != null && !list.isEmpty()) {  
  10. //若list不为空,则将其转换成JSON对象,并存入jsonArray中  
  11. JSONArray jsonArray = JSONArray.fromObject(list);   
  12. //下面就是把存有查询结果的JSON对象返给页面  
  13. response.setContentType("text/html;charset=utf-8");  
  14. PrintWriter out = response.getWriter();  
  15. out.println(jsonArray);  
  16. ……  
  17. }else {……}