Ajax入门

Asynchronous JavaScript And XML (异步的JavaScript和XML),Ajax可以在不刷新页面的前提下,进行页面局部更新,Ajax不是新的技术,Ajax并不是W3C的标准。
在过去,我们在网页中刷新页面内容,需要重新从服务器获取新的页面。
Ajax的出现,揭开了无刷新更新页面的新时代。

Ajax优势

  • 优秀的用户体验:Ajax最大的有点是能在不刷新整个页面的前提下更新数据,这使得Web应用能迅速的回应用户的操作。
  • 提高Web程序的性能:在传统模式中,数据提交是通过表单来实现的,而数据的获取则需要全页面刷新来获取整页内容。Ajax可以不刷新整个页面,按需提交数据给服务器,并接收服务器返回,然后通过dom操作,按需刷新页面的一部分。
  • 减轻服务器和带宽的负担:Ajax的工作原理相当于在用户和服务器之间加了一个中间层,使用户操作与服务器响应异步化。把传统方式下的一些服务器负担的工作转移到了客户端。

    jquery中的ajax

    $ajax()方法是jQuery最底层的Ajax实现。
    结构:$.ajax(options)
    options参数是一个对象:
options参数名称 说明
url 发送请求的地址
type 请求方式(`get post`)
timeout 请求超时时间(毫秒)
data 发送到服务器的数据
datatype 预期服务器返回的数据类型(`text json xml html jsonp script`)
success 请求成功后调用的回调函数
error 请求失败后调用的回调函数
  1. public class News {
  2. private String title;
  3. private String date;
  4. private String source;
  5. private String content;
  6. public News() {
  7. }
  8. public News(String title, String date, String source, String content) {
  9. super();
  10. this.title = title;
  11. this.date = date;
  12. this.source = source;
  13. this.content = content;
  14. }
  15. public String getTitle() {
  16. return title;
  17. }
  18. public void setTitle(String title) {
  19. this.title = title;
  20. }
  21. public String getDate() {
  22. return date;
  23. }
  24. public void setDate(String date) {
  25. this.date = date;
  26. }
  27. public String getSource() {
  28. return source;
  29. }
  30. public void setSource(String source) {
  31. this.source = source;
  32. }
  33. public String getContent() {
  34. return content;
  35. }
  36. public void setContent(String content) {
  37. this.content = content;
  38. }
  39. }
  1. @WebServlet("/news_list")
  2. public class NewsListServlet extends HttpServlet {
  3. private static final long serialVersionUID = 1L;
  4. public NewsListServlet() {
  5. super();
  6. }
  7. protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  8. String type = request.getParameter("t");
  9. List list = new ArrayList();
  10. if(type != null && type.equals("pypl")) {
  11. list.add(new News("PYPL:2018年5月份全球编程语言排行榜" , "2018-5-1" , "PYPL" , "..."));
  12. list.add(new News("PYPL:2018年6月份全球编程语言排行榜" , "2018-6-1" , "PYPL" , "..."));
  13. list.add(new News("PYPL:2018年7月份全球编程语言排行榜" , "2018-7-1" , "PYPL" , "..."));
  14. list.add(new News("PYPL:2018年8月份全球编程语言排行榜" , "2018-8-1" , "PYPL" , "..."));
  15. }else if(type == null || type.equals("tiobe")) {
  16. list.add(new News("TIOBE:2018年5月份全球编程语言排行榜" , "2018-5-1" , "TIOBE" , "..."));
  17. list.add(new News("TIOBE:2018年6月份全球编程语言排行榜" , "2018-6-1" , "TIOBE" , "..."));
  18. list.add(new News("TIOBE:2018年7月份全球编程语言排行榜" , "2018-7-1" , "TIOBE" , "..."));
  19. list.add(new News("TIOBE:2018年8月份全球编程语言排行榜" , "2018-8-1" , "TIOBE" , "..."));
  20. }
  21. String json = JSON.toJSONString(list);
  22. System.out.println(json);
  23. response.setContentType("text/html;charset=UTF-8");
  24. response.getWriter().println(json);
  25. }
  26. }
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Insert title here</title>
  6. <script type="text/javascript" src="js/jquery-3.3.1.js"></script>
  7. <script type="text/javascript">
  8. $(function(){
  9. $.ajax({
  10. "url" : "/ajax/news_list",
  11. "type" : "get" ,
  12. "data" : {"t":"pypl" , "abc":"123" , "uu":"777"},
  13. //"data" : "t=pypl&abc=123&uu=777" ,
  14. "dataType" : "json" ,
  15. "success" : function(json){
  16. console.log(json);
  17. for(var i = 0 ; i < json.length ; i++){
  18. $("#container").append("<h1>" + json[i].title + "</h1>");
  19. }
  20. },
  21. "error" : function(xmlhttp , errorText){
  22. console.log(xmlhttp);
  23. console.log(errorText);
  24. if(xmlhttp.status == "405"){
  25. alert("无效的请求方式");
  26. }else if(xmlhttp.status == "404"){
  27. alert("未找到URL资源");
  28. }else if(xmlhttp.status == "500"){
  29. alert("服务器内部错误,请联系管理员");
  30. }else{
  31. alert("产生异常,请联系管理员");
  32. }
  33. }
  34. })
  35. })
  36. </script>
  37. </head>
  38. <body>
  39. <div id="container"></div>
  40. </body>
  41. </html>

案例:二级联动菜单

public class Channel {
    private String code;
    private String name;

    public Channel() {

    }

    public Channel(String code, String name) {
        super();
        this.code = code;
        this.name = name;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code = code;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

}
@WebServlet("/channel")
public class ChannelServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public ChannelServlet() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String level = request.getParameter("level");
        String parent = request.getParameter("parent");
        List chlist = new ArrayList();
        if(level.equals("1")) {
            chlist.add(new Channel("ai" , "前沿/区块链/人工智能"));
            chlist.add(new Channel("web" , "前端/小程序/JS"));
        }else if(level.equals("2")) {
            if(parent.equals("ai")) {
                chlist.add(new Channel("micro" , "微服务"));
                chlist.add(new Channel("blockchain" , "区块链"));
                chlist.add(new Channel("other" , "..."));
            }else if(parent.equals("web")){
                chlist.add(new Channel("html" , "HTML"));
                chlist.add(new Channel("css" , "CSS"));
                chlist.add(new Channel("other" , "..."));
            }
        }
        String json = JSON.toJSONString(chlist);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(json);
    }
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.3.1.js"></script>
<script type="text/javascript">
    $(function(){
        $.ajax({
            "url" : "/ajax/channel",
            "data" : {"level" : "1"},
            "type" : "get" , 
            "dataType" : "json" , 
            "success" : function(json){
                console.log(json);
                for(var i = 0 ; i < json.length ; i++){
                    var ch = json[i];
                    $("#lv1").append("<option value='" + ch.code + "'>" + ch.name + "</option>")
                }
            }
        })
    })

    $(function(){
        $("#lv1").on("change" , function(){
            var parent = $(this).val();
            console.log(parent);
            $.ajax({
                "url" : "/ajax/channel" , 
                "data" : {"level" : "2" , "parent" : parent},
                "dataType" : "json" , 
                "type" : "get" ,
                "success" : function(json){
                    console.log(json);
                    //移除所有lv2下的原始option选项
                    $("#lv2>option").remove();
                    for(var i = 0 ; i < json.length ; i++){
                        var ch = json[i];
                        $("#lv2").append("<option value='" + ch.code +"'>" + ch.name + "</option>")
                    }
                }
            })
        })
    })
</script>
</head>
<body>
<select id="lv1" style="width:200px;height:30px">
    <option selected="selected">请选择</option>
</select>
<select id="lv2" style="width:200px;height:30px"></select>
</body>
</html>