Extjs使用Ajax对实现后台查询展示

刚开始接触Extjs4.2,准备做个小小的例子实现与后台的交互,搜了网上好多的demo但很少有在页面中查询然后反馈到页面的例子,这个写的时候也出现了好多好多的问题,不过总算能用了。如下`


前台js代码

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%
    String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
            + request.getContextPath() + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="JS/ext/ext-4.2.1/resources/css/ext-all.css">
<script type="text/javascript" src="JS/ext/ext-4.2.1/ext-all.js"></script>
<script type="text/javascript"
    src="JS/ext/ext-4.2.1/locale/ext-lang-zh_CN.js"></script>
<script type="text/javascript"> 
Ext.onReady(function(){

    var  ID = new Ext.form.ComboBox({ //定义id表单对象
        fieldLabel : 'id',
        id : 'id',
        name : 'id', //必须指名name属性.用于将参数传出去//  传值只传name
        allowBlank : true,//设置可以为空
        disabled:false,//是否可编辑,设为可编    
        anchor:'50%',
       store:new Ext.data.ArrayStore({
            fields:['value','text'],        
            data:[["1",'1'],["2",'2'],["3",'3'],["4",'4'],["5",'5']]
    }),
        valueField:'value',   // value 是传值后台对应的id号  
        displayField:'text',   //text是下拉框里显示的id号
        emptyText:'请选择id',
        editable : false,  
        selectOnFocus : true,  
    }); 
    var NAME = new Ext.form.TextField({//表单对象
        fieldLabel : '姓名',
        id:'name',
        name:'name',
        disabled:false,//是否可编辑,
        //height:150,
        allowBlank : true,//设置可以为空
        anchor : '50%'
    }); 
 var ADDRESS = new Ext.form.TextField({//表单对象
    fieldLabel : '地址',
    id:'address',          
    name:'address',//必须指名name属性.用于将参数传出去
    disabled:false,//是否可编辑,
    //height:150,
    allowBlank : true,//设置可以为空
    anchor : '50%',

}); 

    //表单对象
    var   newForm = new Ext.FormPanel({
        id : 'inputForm',
        name : 'inputForm',   
        title: '<center style="curor:hand" onclick="window.location.reload();">查询</center>',
        collapsible : true, //可折叠
        border : true,
        frame: true,
        region : 'center',
        labelWidth : 60, // 标签宽度
        labelAlign : 'right', // 标签对齐方式
        bodyStyle : 'padding:5 5 0', // 表单元素和表单面板的边距
        buttonAlign : 'center',
        autoScroll : true,
         //向后台提交的表单数据
        renderTo: Ext.getBody(),
        items : [ID,NAME,ADDRESS], //传入三个表单对象

        buttons : [
                {
                    text : '查询',
                    handler : function() {
                        var name=Ext.getCmp('id').getValue();

                        Ext.Ajax.request(   
                                {  
                                method:'POST',
                                url:'/Apthisone/ExtjsShow',  //servlet 地址   在servlet包下,但不能写这个地址。
                                dataType:'json',
                                params:{     
                                    id:name,//使用params对象传数据到后台
                                },
                                success:function(response){
                                    var data = Ext.JSON.decode(response.responseText);
                                    //datatype:'text';
                                    //var data=response.responseText; //得到后台对象
                                    //var object={};
                                    //alert(typeof object+""+typeof data);
                                    //alert(data); 
                                    Ext.MessageBox.show({   
                                        title:"查询到id为<"+data.id+">的信息:",
                                        msg:"姓名:"+data.name+" 地址:"+data.address,
                                            buttons:Ext.Msg.OK
                                    });
                                        //Ext.Msg.hide();
                                    Ext.getCmp("name").setValue(data.name);     //后台值展示给页面                      
                                    Ext.getCmp("address").setValue(data.address);                                             
                                },
                                failure:function(){
                                    alert('id不能为空');
                                } 
                                });
                                }               
                }, {
                    text : '取消',
                    handler : function() {
                        memberForm.getForm().reset();

        }
                } ]
    })

});

        </script>
<%-- <script charset="UTF-8" src="<%=basePath%>"></script> --%>
<script type="text/javascript">
        var basePath = '<%=basePath%>';
</script>
<title>页面</title>
</head>
<body>
</body>
</html>

后台servlet


package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.*;
import entiy.User;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class ShowServlet
 */
@WebServlet("/ExtjsShow") // 等价于xml
public class ExtjsShow extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ExtjsShow() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doPost(req, resp);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @SuppressWarnings("unused")
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // TODO Auto-generated method stub
        User user = null;

        UserDAO ud = new UserDAO();
        List<User> list = ud.getAlluser();
        req.setAttribute("list", list);

        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        String str = req.getParameter("id");//前台传入params中的id
        int id = Integer.parseInt(str);

        User user1 = new User();
        user1 = ud.selectUserById(id);  //调用id查询方法  

        String name = user1.getName();
        String address = user1.getAddress();

        JSONObject json = new JSONObject();   //需要引入json-lib  jar包
        try {                            
            json.put("id", id);                 // 把内容写入 json中   
            json.put("name", user1.getName());
            json.put("address", user1.getAddress());
        } catch (Exception e) {
            e.printStackTrace();
        }
        PrintWriter out = resp.getWriter(); 
        // out.println("{name:'name'");

        out.print(json);  //向前台传值



    /*  System.out.println("编号:" + user1.getId());
        System.out.println("姓名:" + user1.getName());
        System.out.println("地址:" + user1.getAddress());
   // 确保根据id后台能查询到
    */  
        out.flush();
        out.close();

    }

    public void init() throws ServletException {
    }

}

前台界面:

查询界面如下:

原始页面

点击查询:
查询



这是自己学习extjs的第一次尝试,写的浅薄了一些,但无论怎样这是一个小小的成果,调试出查询页面时很开心,这个文章做个记录,希望以后自己回来再看已经进步很多。。共勉!

猜你喜欢

转载自blog.csdn.net/qq519423035/article/details/78777854