Home  >  Article  >  Web Front-end  >  Sample code of how javascript requests servlet to implement ajax

Sample code of how javascript requests servlet to implement ajax

黄舟
黄舟Original
2017-06-04 10:36:332131browse

The following editor will bring you an example of javascriptrequestservletimplementing ajax (share). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look.

ajax request is a non-refresh user experience. It can send two asynchronous requests, GET and POST. The current record is as follows:

GET request:

function sendRequestByGet(){
     //定义异步请求对象
    var xmlReq;
    //检测浏览器是否直接支持ajax
    if(window.XMLHttpRequest){//直接支持ajax
      xmlReq=new XMLHttpRequest();
    }else{//不直接支持ajax
      xmlReq=new ActiveObject('Microsoft.XMLHTTP');
    }
    
     //设置回调函数
     xmlReq.onreadystatechange=function(){
       if (xmlReq.readyState==4&&xmlReq.status==200) {
         //获取服务器的响应值
        var result=xmlReq.responseText;
         //后续操作
         alert(result);
      }
     };
     
     //创建异步get请求
     var url="Hello?name=zhangsan";
     xmlReq.open("GET",url,true);
     //发送请求
     xmlReq.send(null);
   }

POST request:

function sendRequestByPost(){
     //定义异步请求对象
    var xmlReq;
    //检测浏览器是否直接支持ajax
    if(window.XMLHttpRequest){//直接支持ajax
      xmlReq=new XMLHttpRequest();
    }else{//不直接支持ajax
      xmlReq=new ActiveObject('Microsoft.XMLHTTP');
    }
    
     //设置回调函数
     xmlReq.onreadystatechange=function(){
       if (xmlReq.readyState==4&&xmlReq.status==200) {
         //获取服务器的响应值
        var result=xmlReq.responseText;
         //后续操作
         alert(result);
      }
     };
     
     //创建异步Post请求
     var url="Hello";
     xmlReq.open("POST",url,true);
     xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
     //发送请求
     var data="name=lisi";
     xmlReq.send(data);
   }

ajax requested servlet:

@Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    String name=req.getParameter("name");
    PrintWriter out = resp.getWriter();
    out.print(name);
  }

Effect:

The above is the detailed content of Sample code of how javascript requests servlet to implement ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn