[代码] [JavaScript]代码
01 | 1、在HTML中,有这样一个表单: |
02 | |
03 | <form method= "post" name= "searchform" id= "searchform" method= "/sek.go" > |
04 | <input name= "query" value= "" type= "text" id= "query" /> |
05 | <input type=”submit” value= "查询" ></input> |
06 | </form> |
07 | |
08 | |
09 | 当然,要想在HTML中使用Js功能,必须在<head/>中加入 |
10 | |
11 | <script type= "text/javascript" src= "/style/js/ajax.js" ></script> |
12 | |
13 | |
14 | 2、然后在ajax.js文件中加入如下代码 |
15 | |
16 | function userSearch(){ |
17 | |
18 | var query = $( "#searchform input[@name='query']" ).val(); |
19 | |
20 | |
21 | $.post( "/userSearch.htm" , { query: query } , function callback(json){ |
22 | |
23 | var userlist = $.parseJSON(json); |
24 | |
25 | userList(userlist); |
26 | |
27 | }); |
28 | |
29 | } |
30 | |
31 | /******************************************* |
32 | 解释如下: |
33 | |
34 | 1)、"#searchform input[@name='query']";的意思是: 选择id为searchform其下的(name属性值为’query’的)input标签 |
35 | |
36 | 2)、$(“”).val()意为要得到(“”)所选中属性的值; |
37 | |
38 | 3)、在$.post()中,第一项参数是指定目标servlet,即要把本post请求发给的那个servlet。 |
39 | |
40 | 第二项是本post请求所携带的数据;“:”前的为key或者name,后为value; |
41 | |
42 | 第三项是回调函数,其内若有形参,则表示要对从servlet返回的值进行处理,这里的callback的功能是将JSON对象json转换成了JS对象userlist,然后将JS对象传入函数userList |
43 | |
44 | 3、post请求携带了名为query的参数去了后台,在servlet中进行处理: |
45 | |
46 | //从名为"query"能的参数中取出post带过来的数据 |
47 | String query = request.getParameter("query"); |
48 | if (query != null && !query.isEmpty() |
49 | && !query.trim().equalsIgnoreCase("")) { |
50 | //如果"query"的值不为空,就用'query'为参数构建HQL语句 |
51 | String hql = "from TUser as user where user.userName like '"+ query + "%'"; |
52 | //到库表TUser中进行查询,并得到一个表结构 |
53 | List list = weilav3TUserDAO.getListByHQL(hql); |
54 | if (list != null && !list.isEmpty()) { |
55 | //若list不为空,则将其转换成JSON对象,并存入jsonArray中 |
56 | JSONArray jsonArray = JSONArray.fromObject(list); |
57 | //下面就是把存有查询结果的JSON对象返给页面 |
58 | response.setContentType("text/html;charset=utf-8"); |
59 | PrintWriter out = response.getWriter(); |
60 | out.println(jsonArray); |
61 | …… |
62 | }else {……} |
63 | **************/ |