首页 > 技术文章 > jQuery与Ajax入门

jessekkk 2020-04-27 20:47 原文

jQuery

JavaScript库

jQuery介绍

jQuery选择器

基本选择器

层叠选择器

属性选择器

位置选择器

表单选择器

操作元素属性

操作元素CSS属性

设置元素内容

jQuery中的事件及处理

Ajax

Ajax的介绍

Ajax使用

创建与发送

处理响应

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <input id="btnload"  type= "button"  value="加载">
    <div id="divContent"></div>
    <script>
        document.getElementById("btnload").onclick = function(){
            //1. 创建XMLHttpRequest对象
            var xmlhttp;
            if(window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest();
            }else{
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            console.log(xmlhttp);
            //2. 发送Ajax请求
            xmlhttp.open("GET", "/ajax/content", true);
            xmlhttp.send();
            //3. 处理服务器响应
            xmlhttp.onreadystatechange = function(){
                if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                    var t = xmlhttp.responseText;
                    alert(t);
                    document.getElementById("divContent").innerHTML = t;
                }
            }
        }
    </script>
</body>
</html>

利用Ajax实现新闻列表

package com.jesse.ajax;

public class News {
    private String title;
    private String date;
    private String source;
    private String content;

    public News() {
    }

    public News(String title, String date, String source, String content) {
        super();
        this.title = title;
        this.date = date;
        this.source = source;
        this.content = content;
    }
    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;
    }

}
package com.jesse.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 {
        List<News> list = new ArrayList<News>();
        list.add(new News("TIOBE:2018年5月全球编程语言排行", "2018-5-1", "TIOBE", "..."));
        list.add(new News("TIOBE:2018年6月全球编程语言排行", "2018-5-1", "TIOBE", "..."));
        list.add(new News("TIOBE:2018年7月全球编程语言排行", "2018-5-1", "TIOBE", "..."));
        list.add(new News("TIOBE:2018年8月全球编程语言排行", "2018-5-1", "TIOBE", "..."));
        list.add(new News("TIOBE:2018年9月全球编程语言排行", "2018-5-1", "TIOBE", "..."));
        String json =JSON.toJSONString(list);
        System.out.println(json);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println(json);
    }

}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <div id="container">
    </div>
<script type="text/javascript">
    //1. 创建XMLHttpRequest
    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //2. 发送Ajax请求
    xmlhttp.open("GET", "/ajax/news_list", true);
    xmlhttp.send();
    //3. 处理服务器响应
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            var text = xmlhttp.responseText;
            console.log(text);
            var json = JSON.parse(text);
            console.log(json);
            var html = "";
            for(var i = 0 ; i < json.length; i++){
                var news = json[i];
                html = html + "<h1>" + news.title + "</h1>";
                html = html + "<h2>" + news.date + "&nbsp;" + news.source + "</h2>";
                html = html + "<hr/>";
            }
            document.getElementById("container").innerHTML = html;
        }
    }
</script>
</body>
</html>

同步与异步的区别

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <div id="container">
    </div>
<script type="text/javascript">
    //1. 创建XMLHttpRequest
    var xmlhttp;
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
    }else{
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //2. 发送Ajax请求
    //true 代表异步执行  false 代表同步执行
    xmlhttp.open("GET", "/ajax/news_list", true);
    xmlhttp.send();
    console.log("请求发送完成");
    /*同步处理代码
    if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
        var text = xmlhttp.responseText;
        console.log(text);
        var json = JSON.parse(text);
        console.log(json);
        var html = "";
        for(var i = 0 ; i < json.length; i++){
            var news = json[i];
            html = html + "<h1>" + news.title + "</h1>";
            html = html + "<h2>" + news.date + "&nbsp;" + news.source + "</h2>";
            html = html + "<hr/>";
        }
        document.getElementById("container").innerHTML = html;
    }*/
    //3. 处理服务器响应
    xmlhttp.onreadystatechange = function(){
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
            var text = xmlhttp.responseText;
            console.log(text);
            var json = JSON.parse(text);
            console.log(json);
            var html = "";
            for(var i = 0 ; i < json.length; i++){
                var news = json[i];
                html = html + "<h1>" + news.title + "</h1>";
                html = html + "<h2>" + news.date + "&nbsp;" + news.source + "</h2>";
                html = html + "<hr/>";
            }
            document.getElementById("container").innerHTML = html;
        }
    }
</script>
</body>
</html>

jQuery对Ajax的支持

介绍

Ajax的使用

<!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(){
        $.ajax({
            "url" : "/ajax/news_list",
            "type" : "post",
            //"date" : {"t" : "pypl", "abc" : "123", "uu" : "777"},
            "data" : "t=pypl",
            "dataType" : "json",
            "success" : function(json){
                console.log(json);
                for(var i = 0; i < json.length; i++){
                    console.log(json[i].title);
                    $("#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>
    <p></p>
</body>
</html>

后台数据实现二级联动菜单

package com.jesse.ajax;

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;
    }


}
package com.jesse.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 ChannelServlet
 */
@WebServlet("/channel")
public class ChannelServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public ChannelServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String level = request.getParameter("level");
        String parent = request.getParameter("parent");
        List<Channel> chlist = new ArrayList<Channel>();
        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.4.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").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>

推荐阅读