7 jquery中ajax

 // 标准ajax
      $.ajax({
        
         type:'POST',    //type:请求方式get或者是post
         url:'/jquery_demo1/demoServlet', //url:请求地址
         async:false,       // 同步的ajax
         data:{name:'aa'},    //data:发送的数据
         dataType:'text' ,    //dataType:返回的数据类型,有json,text,xml,html
         success:function(responseText){  //success:回调的数据方法
             
            alert(responseText) ;
         },
      
         error:function(){
             alert('发生错误');             //error:发生错误时
         }  
          
      });

ajax.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"   pageEncoding="UTF-8"%>






Insert title here








MyServlet.java

public class MyServlet extends HttpServlet {
       @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
           //获得ajax发送的数据
        String name= req.getParameter("username");
        Person p = new Person();
        p.setId(1);
        p.setAge(20);
        p.setName("张三");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //String result="{\"id\":"+p.getId()+",\"name\":\""+p.getName()+"\",\"age\":"+p.getAge()+"}"; //太麻烦  拼json串
         //直接使用json库
         JSONObject obj = JSONObject.fromObject(p);
         resp.getWriter().print(obj);
           
    }
    
       
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        this.doGet(req, resp);
    }
}

web.xml配置

ajax1.jsp









ValidServlet

public class ValidServlet extends HttpServlet {
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
             //获得ajax3发送的数据
            String name=req.getParameter("uname");
            if("12345".equals(name)){
                resp.getWriter().print("yes");
            }else{
                resp.getWriter().print("no");

            }
        }
        
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
             this.doPost(req, resp);
        }

}

ajaxvalid.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>






Insert title here




用户名:

密码:

地址:

效果如下:

你可能感兴趣的:(7 jquery中ajax)