05Ajax总结

Ajax

综合理解

目的就是现实页面局部刷新,也就是不是重新打开窗口。而是在当前窗口改变内部的一小部分。比如看视频的时候中途登录会员,页面不会重新刷新将你现在看到一半的电影回到起点,而是接着正在看的地方继续看,只是登录会员那里做了改变。传统的请求方式是会将页面刷新,回到电影起点。同时ajax是支持异步的。也就是说在提交数据的时候(这个时候可能出现很慢的时候),可以做别的事情,比如单击页面的其他按钮,传统的请求方式是将窗口锁定,是不能点击页面的其他按钮的。

快速入门:实现四步

  • 创建AJAX核心对象

  • 注册回调函数

  • 开启通道

  • 发送请求

<script type="text/javascript">
    function listProvince() {
        //1.创建AJAX核心对象XMLHttpRequest(浏览器内置的,可以直接使用)
        var xhr = null;
        if (window.XMLHttpRequest){
            xhr = new XMLHttpRequest();
        } else {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        }
        //2.注册回调函数
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4){
                if (xhr.status == 200){
                    //接收服务器端返回的json
                    //eval作用:将服务器端构建好的JSON数据转化为可用的JavaScript对象
                    var jsonString = xhr.responseText;
                    alert("var arr = " + jsonString);
                    eval("var arr = " + jsonString);
                    //遍历数组
                    var html = "<option value=''>---请选择省份---</option>";
                    for (var i = 0 ; i < arr.length ; i++){
                        var provinceJson = arr[i];
                        html += "<option value ='" + provinceJson.id + "'>" + provinceJson.province + "</option>";
                    }
                    //$("#provinceList").html(html);
                    document.getElementById("provinceList").innerHTML = html;
                }else {
                    alert(xhr.status);
                }
            }
        }
        //3.开启浏览器和服务器之间的通道
        xhr.open("GET" , "/s/province/find",true);
        //4.发送AJAX请求
        xhr.send();
    }

详细理解

1.什么是Ajax?

​ Asynchronous Javascript And Xml

​ 异步的JavaScript和XML

​ AJAX不是一个技术,是多个技术联合实现的产物。

2.AJAX是浏览器客户端上的前端技术。

注意:只要是做web开发,B/S架构的,不管服务器端编程语言是哪一种,前端AJAX都是要学习的。

​ 做PHP开发,AJAX也得学习。

3.异步和同步有什么区别?

​ A线程和B线程,并发执行,谁也不等谁,这就是异步。

​ A线程和B线程,在A线程执行的时候B线程需要等待,或者B线程执行的时候A线程需要等待,这就是同步。

4.传统的请求和Ajax请求有什么区别?

​ 传统的请求:都是同步的。

​ Ajax请求:可以做到异步。

5.AJAX经典的案例

​ Google的auto complete(输入框的自动补全)

​ Google的map(谷歌地图)

6.注意和ajax请求过程

​ 浏览器本身这个软件也是支持多线程并发的。其中ajax请求就是一个线程。一个页面上可以同时发送多个ajax请求。多个ajax请求对应浏览器多个线程。当整个浏览器采用的是传统请求的时候,请求只要一发送,整个浏览器窗口锁定,无法点击其他按钮,并且浏览器会将窗口当中的数据全部清除,迎接新的页面。

7.AJAX主要解决的问题

​ 页面的局部刷新问题。

​ 使用ajax可以在同一个网页当中并发的发送多个请求。请求与请求之间互不等待,这样可以提高用户的体验。

8.用户体验

​ AJAX异步请求用户的体验在浏览器上不存在间断期,用户体验不间断。

​ 传统的请求,由于整个页面会被全部清除,有一个空白期,用户的体验是间断的。

​ (现代的开发中:多数请求都是ajax,但传统请求也会存在,并行的。)

9.传统AJAX编程四步:

  • 创建AJAX核心对象
  • 注册回调函数
  • 开启通道
  • 发送请求

10.基于jquery的ajax实现

插曲:setInterval(quoto,5000);js中表示每隔5秒执行quoto这个function

正文:

jquery对ajax的支持

(1)$.ajax()方法–利用jquery提供的方法来向服务器发送异步请求。

用法:$.ajax({});

说明:{}是一个用来描述请求选项参数的对象。常见的选项参数有如下几个:

  • url:请求地址
  • data:请求参数,有两种格式(服务器端可以通过getParamter方法来获得该中的值):
    • 请求字符串,比如:“adminCode = lichen”
    • 对象,比如:{“adminCode”:“lichen”,“age”:age}(说明这里第二个age是页面中的变量var)
  • type:请求类型(get/post)
  • dataType:服务器返回数据的类型:
    • text:文本数据
    • json:json字符串
    • html:html文档
    • xml:xml文档
    • script:JavaScript脚本
  • success:时间处理函数(当服务器处理正常,用来处理服务器返回数据。相当于传统的if (xhr.readyState == 4&&xhr.status == 200)。书写格式【“success”:function(服务器端返回的数据){方法体} 】注意这里的返回数据如果dataType的值为json则该ajax方法会将服务端传来的json数据自动转为js对象。进而使得我们方便进一步通过jquery等直接操作js对象,获取后台的数据。
  • error:事件处理函数(当服务器处理异常,用来处理服务器返回的数据,同success格式类型,若只写一个参数,则是XMLHttpRequest对象,可以直接alert看看,或者对该对象操作)

(2)load()

作用:向服务器发送异步请求,然后将服务器返回的数据直接添加到符合要求的节点之上。load用于简单的,也就是后端直接返回数据,然后前端直接innerHtml赋值的这种。

用法:

$obj.load(url,[data]);

注意:

url:请求地址

data:同上

o b j − − − − − − 例 如 obj ------例如 obj("#a1").load(“提交路径”);

案例理解

https://www.cnblogs.com/fxxkhigh/p/5669904.html

$.ajax({
  url: 'www.baidu.com/getInfo',
  type: 'POST',
  data: {
    name: 'jack',
    age: 18
  },
  dataType: 'json',
  success: function(resp){
  // callback
  },
  error: function(err){
  // error code
  }    
});

传统实现

1.省级联动(传统ajax+mybatis+springMVC)

1.数据库设计
在这里插入图片描述在这里插入图片描述

2.案例文件结构
在这里插入图片描述

3.依赖jar包Maven,直接pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.sz.ajax</groupId>
  <artifactId>Ajax</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>Ajax Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  
  <dependencies>
    <!--测试类依赖-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!--测试类依赖结束-->
    <!--MySQL依赖-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.38</version>
    </dependency>
    <!--MySQL依赖结束-->
    <!--mybatis依赖-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>
    <!--mybatis依赖结束-->
    <!--springMVC和spring的依赖-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>
    <!--springMVC和spring依赖结束-->
    <!--实现springMVC与json数据交互的-->
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.3</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.3</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.3</version>
    </dependency>
    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
    </dependency>
    <!--交互结束-->
    <!--添加处理json为Javabean-->
      <dependency>
          <groupId>org.codehaus.jackson</groupId>
          <artifactId>jackson-core-asl</artifactId>
          <version>1.9.2</version>
      </dependency>
    <dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.2</version>
    </dependency>
    <!--添加处理json为Javabean结束-->
    <!--添加servlet,用于HttpServletRequest获取前台url中的参数getParameter-->
      <dependency>
          <groupId>javax.servlet</groupId>
          <artifactId>javax.servlet-api</artifactId>
          <version>3.1.0</version>
      </dependency>
  </dependencies>

  <build>
    <finalName>Ajax</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

4.Pojo

City.java

package com.sz.pojo;

public class City {
    private Integer id;
    private String city;
    private Province province;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Province getProvince() {
        return province;
    }

    public void setProvince(Province province) {
        this.province = province;
    }

    @Override
    public String toString() {
        return "City{" +
                "id=" + id +
                ", city='" + city + '\'' +
                ", province=" + province +
                '}';
    }
}

Province.java

package com.sz.pojo;

public class Province {
    private Integer id;
    private String province;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    @Override
    public String toString() {
        return "Province{" +
                "id=" + id +
                ", province='" + province + '\'' +
                '}';
    }
}

5.utils

MybatisUtil

package com.sz.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {

    private static SqlSessionFactory sqlSessionFactory;//保证了单例??

    static{
        String resource = "mybatis.cfg.xml";
        InputStream in = null;
        try {
            in = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(in);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static SqlSession getSession(){

        return sqlSessionFactory.openSession();
    }
}

6.mapper

CityMapper

package com.sz.mapper;

import com.sz.pojo.City;
import com.sz.pojo.Province;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface CityMapper {
    public List<City> queryById(@Param("id") Integer id)throws Exception;
}

ProvinceMapper

package com.sz.mapper;

import com.sz.pojo.Province;

import java.util.List;

public interface ProvinceMapper {
    public List<Province> queryById()throws Exception;
}

7.Controller

CityController

package com.sz.controller;

import com.sz.mapper.CityMapper;
import com.sz.mapper.ProvinceMapper;
import com.sz.pojo.City;
import com.sz.pojo.Province;
import com.sz.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/city")
public class CityController {
    @RequestMapping("/find")
    @ResponseBody
    public List<City> findCity(HttpServletRequest request) throws Exception {
        int id = Integer.valueOf(request.getParameter("id"));
        System.out.println(id);
        SqlSession session = MybatisUtil.getSession();
        CityMapper mapper = session.getMapper(CityMapper.class);
        List<City> cities = mapper.queryById(id);
        System.out.println(cities);
        return cities;
    }
}

ProvinceController.java

package com.sz.controller;

import com.sz.mapper.CityMapper;
import com.sz.mapper.ProvinceMapper;
import com.sz.pojo.City;
import com.sz.pojo.Province;
import com.sz.util.MybatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/province")
public class ProvinceController {
    @RequestMapping("/find")
    @ResponseBody
    public List<Province> find() throws Exception {
        SqlSession session = MybatisUtil.getSession();
        ProvinceMapper mapper = session.getMapper(ProvinceMapper.class);
        List<Province> provinces = mapper.queryById();
        System.out.println(provinces);
        return provinces;
    }

}

8.mapper.xml

City.mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper  namespace="com.sz.mapper.CityMapper">


    <select id="queryById" resultType="com.sz.pojo.City">
        select *
        from citytable
        <where>
            <if test="id != null">
                and pid = #{id}
            </if>
        </where>
    </select>
</mapper>

Province.mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper  namespace="com.sz.mapper.ProvinceMapper">


    <select id="queryById" resultType="com.sz.pojo.Province">
      select *
      from provincetable
    </select>
</mapper>

9.properties

url=jdbc:mysql://localhost:3306/pc
username=root
password=123456
driver=com.mysql.jdbc.Driver

10.mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"
>

    <!--配置一个注解扫描包,也就是说激活注解-->
    <context:component-scan base-package="com.sz.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--默认的servlet处理者,这样的话识别静态资源,然后由Tomcat处理,非静态资源由springMVC处理-->
    <mvc:default-servlet-handler/>
    <!--只加上上面一个,相当于全部(RequestMapping里面的路径)让它处理了。也就是说让前面的注解扫描包失效了。-->
    <mvc:annotation-driven/>
    <!--不正确,理解是对该资源下的文件进行由Tomcat自行处理,不由MVC处理-->
    <mvc:resources mapping="/static/css/*" location="/static/css/"/>
</beans>

11.mybatis.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <properties resource="jdbc.properties">
    </properties>

    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    
    <environments default="dev">
        <environment id="dev">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="UNPOOLED">
                <property name="url" value="${url}"/>
                <property name="driver" value="${driver}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <!--不要写. 要写斜杠,路径的时候要写斜杠/,.法是写class的-->
        <!--第一种:通过类路径方式引入XML文件-->
        <!--<mapper resource="com/sz/mapper/GirlMapper.xml"/>-->
        <!--第二种:通过URL 协议:地址的方式引入-->
        <!--<mapper url="file:///D:/IDEA_Test/mybatis0002/src/main/resources/com/sz/mapper/GirlMapper.xml"/>-->
        <!--第三种:通过接口的全限定名引入,必须保持我们的接口和Mapper.xml在同包之下-->
        <!--<mapper class="com.sz.mapper.GirlMapper"/>-->
        <!--第四种:引入一个包的方式,以后只要是在这个包下新建的Mapper,不需要重新引入-->
        <package name="com.sz.mapper"/>
    </mappers>
</configuration>

12.web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">


    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- characterEncodingFilter字符编码过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <!--要使用的字符集,一般我们使用UTF-8(保险起见UTF-8最好)-->
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <!--是否强制设置request的编码为encoding,默认false,不建议更改-->
            <param-name>forceRequestEncoding</param-name>
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <!--是否强制设置response的编码为encoding,建议设置为true,下面有关于这个参数的解释-->
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <!--这里不能留空或者直接写 ' / ' ,否者不起作用-->
        <url-pattern>/*</url-pattern>
    </filter-mapping>


    <!--注册一个支持所有http请求类型的过滤器-->
    <filter>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

pc.jsp

<%--
  Created by IntelliJ IDEA.
  User: lichen
  Date: 2019/4/11
  Time: 18:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <%--<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>--%>
    <title>省市联动</title>
</head>
<body "listProvince();">
    <button id="b1">请求得到一个List</button>

    <script type="text/javascript">

        function listProvince() {
            //1.创建AJAX核心对象XMLHttpRequest(浏览器内置的,可以直接使用)
            var xhr = null;
            if (window.XMLHttpRequest){
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            //2.注册回调函数
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4){
                    if (xhr.status == 200){
                        //接收服务器端返回的json
                        var jsonString = xhr.responseText;
                        alert("var arr = " + jsonString);
                        eval("var arr = " + jsonString);
                        //遍历数组
                        var html = "<option value=''>---请选择省份---</option>";
                        for (var i = 0 ; i < arr.length ; i++){
                            var provinceJson = arr[i];
                            html += "<option value ='" + provinceJson.id + "'>" + provinceJson.province + "</option>";
                        }
                        //$("#provinceList").html(html);
                        document.getElementById("provinceList").innerHTML = html;
                    }else {
                        alert(xhr.status);
                    }
                }
            }
            //3.开启浏览器和服务器之间的通道
            xhr.open("GET" , "/s/province/find",true);
            //4.发送AJAX请求
            xhr.send();
        }
        function listCitys(id) {
            alert(id);
            //1.创建AJAX核心对象XMLHttpRequest(浏览器内置的,可以直接使用)
            var xhr = null;
            if (window.XMLHttpRequest){
                xhr = new XMLHttpRequest();
            } else {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            //2.注册回调函数
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4){
                    if (xhr.status == 200){
                        //接收服务器端返回的json
                        var jsonString = xhr.responseText;
                        alert("var arr = " + jsonString);
                        eval("var arr = " + jsonString);
                        //遍历数组
                        var html = "<select><option value=''>---请选择市份---</option>";
                        for (var i = 0 ; i < arr.length ; i++){
                            var cityJson = arr[i];
                            html += "<option value ='" + cityJson.id + "'>" + cityJson.city + "</option>";
                        }
                        html += "</select>";
                        //$("#provinceList").html(html);
                        document.getElementById("citySpan").innerHTML = html;
                    }else {
                        alert(xhr.status);
                    }
                }
            }
            //3.开启浏览器和服务器之间的通道
            xhr.open("GET" ,"/s/city/find?id="+ id,true);
            //4.发送AJAX请求
            xhr.send();
        }
    </script>

    <%--省份放到下拉列表当中--%>
    <select id="provinceList" "listCitys(this.value);">
    </select>
    <span id="citySpan">
    </span>
</body>
</html>

使用基于jquery的ajax实现

更改的结构
在这里插入图片描述

pc.jsp

<%--
  Created by IntelliJ IDEA.
  User: lichen
  Date: 2019/4/11
  Time: 18:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <%--<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>--%>
    <%--最好写在js文件夹下,然后以/s/js---也就是说从/项目名开始找寻js文件--%>
    <script type="text/javascript" src="/s/js/jquery-1.3.2.js"></script>
    <title>省市联动</title>
</head>
<body>
    <%--省份放到下拉列表当中--%>
    <select id="provinceList" "listCitys(this.value);">
    </select>
    <span id="citySpan">
        <select id="cityNum">
            <option>---请选择市区---</option>
        </select>
    </span>

    <button id="b1">请求得到一个List</button>
    <button id="b2">请求得到一个List</button>

    <script type="text/javascript">
            $("#b1").click(function () {
                alert("aaa");
            });
            $("#b2").click(function () {
                alert("bbb");
            });
            $.ajax({
                "url":"/s/province/find",
                "type":"get",
                "contentType":"application/json",
                "dataType":"json",
                "success":function (provinces) {
                    $("#provinceList").append("<option value='0'>---请选择省份---</option>");
                    for (var i = 0; i < provinces.length; i++){
                        $("#provinceList").append("<option value='" + provinces[i].id + "'>" + provinces[i].province + "</option>");
                    }
                },
                "error":function (err) {
                    alert(err);
                }
            });
            function listCitys(cityId){
                $.ajax({
                    "url":"/s/city/find",
                    "type":"get",
                    "contentType":"application/json",
                    "dataType":"json",
                    "data":{id:cityId},
                    "success":function (citys) {
                        $("#cityNum").empty();
                        $("#cityNum").append("<option>---请选择市区---</option>");
                        for (var i = 0; i < citys.length; i++){
                            $("#cityNum").append("<option>" + citys[i].city + "</option>");
                        }
                    },
                    "error":function (err) {
                        alert(err);
                    }
                });
            }
    </script>
</body>
</html>

零碎补充

对于js,数组的长度的属性是length

jquery的empty方法用来清空当前节点innerHtml中的内容,也就是最后只能留下该节点的开始和结束标签而已

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值