35 jQuery对Ajax的支持

image.png

image.png
//News.java
package com.imooc.ajax;

public class News {
    private String title;
    private String date;
    private String source;
    private String content;
    public News(String title, String date, String source, String content) {
        super();
        this.title = title;
        this.date = date;
        this.source = source;
        this.content = content;
    }
    public News() {
        
    }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getDate() {
        return date;
    }
    public void setDate(String date) {
        this.date = date;
    }
    public String getSource() {
        return source;
    }
    public void setSource(String source) {
        this.source = source;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    
    
}

//NewsListServlet.java
package com.imooc.ajax;

import java.io.IOException;
import java.util.ArrayList;
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 com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class NewsListServlet
 */
@WebServlet("/news_list")
public class NewsListServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public NewsListServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("t");
        List newsList = new ArrayList();
        if(type != null && type.equals("pypl")) {
            newsList.add(new News("PYPL:全球编程语言排行榜5月","2018-5-1","PYPL","..."));
            newsList.add(new News("PYPL:全球编程语言排行榜6月","2018-5-1","PYPL","..."));
            newsList.add(new News("PYPL:全球编程语言排行榜7月","2018-5-1","PYPL","..."));
            newsList.add(new News("PYPL:全球编程语言排行榜8月","2018-5-1","PYPL","..."));
        }else if(type == null || type.equals("tiobe")) {
            newsList.add(new News("TIOBE:全球编程语言排行榜5月","2018-5-1","TIOBE","..."));
            newsList.add(new News("TIOBE:全球编程语言排行榜6月","2018-5-1","TIOBE","..."));
            newsList.add(new News("TIOBE:全球编程语言排行榜7月","2018-5-1","TIOBE","..."));
            newsList.add(new News("TIOBE:全球编程语言排行榜8月","2018-5-1","TIOBE","..."));
        }
        
        
        
        String json = JSON.toJSONString(newsList);
        System.out.println(json);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println(json);
    }

}

//jquery_news.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
    $(function(){     //页面就绪函数,页面加载完成后执行function里面的代码
         $.ajax({
             "url":"/Ajax/news_list",
             "type":"get",//post 依然会自动用表单传递参数
             "data":"t=pypl",
            //对于data多个参数:
            //1."data":"t=pypl&abc=123&uu=777",
            //2."data":{"t":"pypl","abc":"123","uu":"777"},  //推荐
             "dataType":"json",//text,则不会解析为json
             "success":function(json){ //对响应的json文本自动进行解析
                console.log(json);
                for(var i=0;i<json.length;i++){
                    $("#container").append("<h1>" + json[i].title + "</h1>");//追加到指定元素中
                }    
             },
             "error":function(xmlhttp,errorText){
                 console.log(xmlhttp);
                 console.log(errorText);
                 if(xmlhttp.status == "405"){
                     alert("无效的请求方法");
                 }else if(xmlhttp.status == "404"){
                     alert("未找到URL资源");
                 }else if(xmlhttp.status == "500"){
                     alert("服务器内部错误,请联系管理员");
                 }else{
                     alert("产生异常,请联系管理员");
                 }
             }
         })
    })
</script>
</head>
<body>
    <div id="container"></div>
</body>
</html>

地址栏输入http://localhost:8080/Ajax/jquery_news.html

一个小练习

image.png
package com.imooc.ajax;

import java.util.List;

public class Song {
    private List popMusic;
    private List classMusic;
    private List rockMusic;
    public Song() {
        
    }
    
    public Song(List popMusic, List classMusic, List rockMusic) {
        super();
        this.popMusic = popMusic;
        this.classMusic = classMusic;
        this.rockMusic = rockMusic;
    }

    public List getPopMusic() {
        return popMusic;
    }
    public void setPopMusic(List popMusic) {
        this.popMusic = popMusic;
    }
    public List getClassMusic() {
        return classMusic;
    }
    public void setClassMusic(List classMusic) {
        this.classMusic = classMusic;
    }
    public List getRockMusic() {
        return rockMusic;
    }
    public void setRockMusic(List rockMusic) {
        this.rockMusic = rockMusic;
    }
    
}

package com.imooc.ajax;

import java.io.IOException;
import java.util.ArrayList;
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 com.alibaba.fastjson.JSON;

/**
 * Servlet implementation class SongServlet
 */
@WebServlet("/song")
public class SongServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SongServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        List<String> popList = new ArrayList();
        popList.add("稻香");
        popList.add("晴天");
        popList.add("告白气球");
        List<String> classicList = new ArrayList();
        classicList.add("千千厥歌");
        classicList.add("傻女");
        classicList.add("七友");
        List<String> rockList = new ArrayList();
        rockList.add("一块红布");
        rockList.add("假行僧");
        rockList.add("新长城路上的摇滚");
        
        Song songs = new Song(popList,classicList,rockList);
        String json = null;
        if(type.equals("pop")) {
            json = JSON.toJSONString(songs.getPopMusic());
        }else if(type.equals("classic")) {
            json = JSON.toJSONString(songs.getClassMusic());
        }else if(type.equals("rock")) {
            json = JSON.toJSONString(songs.getRockMusic());
        }else {
            System.out.println("类型错误");
            return;
        }
        System.out.println(json);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().println(json);
    }

}

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <input type="button" name="pop" value="流行歌曲">
    <input type="button" name="classic" value="经典歌曲">
    <input type="button" name="rock" value="摇滚歌曲">
    <div id="container"></div>
    <script type="text/javascript" src="js/jquery-3.4.1.js"></script>
    <script type="text/javascript">
        $("input[name='pop']").click(function(){
            $.ajax({
                "url":"/Ajax/song",
                "type":"get",
                "data":"type=pop",
                "dataType":"json",
                "success":function(json){
                    console.log(json);
                    $("#container").text("");
                    for(var i=0;i<json.length;i++){
                        $("#container").append("<h1>"+json[i]+"</h1>");
                    }
                }
            });
        });
        
        $("input[name='classic']").click(function(){
            $.ajax({
                "url":"/Ajax/song",
                "type":"get",
                "data":"type=classic",
                "dataType":"json",
                "success":function(json){
                    console.log(json);
                    $("#container").text("");
                    for(var i=0;i<json.length;i++){
                        $("#container").append("<h1>"+json[i]+"</h1>");
                    }
                }
            });
        });
        $("input[name='rock']").click(function(){
            $.ajax({
                "url":"/Ajax/song",
                "type":"get",
                "data":"type=rock",
                "dataType":"json",
                "success":function(json){
                    console.log(json);
                    $("#container").text("");
                    for(var i=0;i<json.length;i++){
                        $("#container").append("<h1>"+json[i]+"</h1>");
                    }
                }
            });
        });
        
    </script>
    
    
    
</body>
</html>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • AJAX 原生js操作ajax 1.创建XMLHttpRequest对象 var xhr = new XMLHtt...
    碧玉含香阅读 3,264评论 0 7
  • 详细解读Jquery各Ajax函数: $.get(),$.post(),$.ajax(),$.getJSON() ...
    远方不会远阅读 1,039评论 0 10
  • 1. 什么是同源策略 浏览器限制不同源的两个网站间脚本和文本的相互访问,只允许访问同源下的内容。所谓同源,就是指两...
    熊蛋子17阅读 698评论 1 6
  • 第一章 入门 基本功能:访问和操作 dom 元素,控制页面样式,对页面的事件处理,与ajax完美结合,有丰富的插件...
    X_Arts阅读 1,066评论 0 2
  • 一、简历准备 1、个人技能 (1)自定义控件、UI设计、常用动画特效 自定义控件 ①为什么要自定义控件? Andr...
    lucas777阅读 5,244评论 2 54