ajax (原生实现 与 jquery实现)

1 原生javascript实现ajax请求  参见w3c  "值得注意的是写请求路径是:一定不需要加 / “

<script type="text/javascript">

  function fun() {
    var xmlhttp;
    if(window.XMLHttpRequest){
      xmlhttp = new XMLHttpRequest();
    }else {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //get 、post
    xmlhttp.open("get","ajaxServlet?username='i am parameter'",true);
    xmlhttp.send();

    //获取回转过来的响应
    xmlhttp.onreadystatechange=function()
    {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
        document.getElementById("p").innerHTML=xmlhttp.responseText;
      }
    }

  }
存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。

0: 请求未初始化
1: 服务器连接已建立
2: 请求已接收
3: 请求处理中
4: 请求已完成,且响应已就绪

200: "OK"

404: 未找到页面

  

</script>
@WebServlet("/ajaxServlet")
public class AjaxServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("username");
        System.out.println(username);
        response.getWriter().write("hello im server");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

2 Jquery实现ajax交互

$.ajax( { } )

function fun2() {
    $.ajax({
      url:"ajaxServlet",
      type:"post",
      data:{"username":"jack","age":33},
      success:function(data){
        alert(data);
      }
    });
  }

$.Get("请求路径","请求参数{}","回调函数","返回数据的格式")

$.Post("请求路径","请求参数{}","回调函数","返回数据的格式")

回调函数: 

  • data- 包含来自请求的结果数据
  • status - 包含请求的状态
  • xhr - 包含 XMLHttpRequest 对象

返回数据的格式:可能的类型:"xml"     "html"   "text"    "script"    "json"    "jsonp"

  function fun3() {
    $.get("ajaxServlet",{"username":"rose"},function (data) {
      alert(data)
    },"json");   //注意:这里一定要写返回值的类型!!!不然会出现你想不到的问题   或者在服务器端书写contextType的类型指定为“application/json”类型
  }
坚持
原文地址:https://www.cnblogs.com/gaoSJ/p/12937166.html