ajax使用案例

1.index.jsp页面:

下边是采用JavaScript的ajax发出异步请求。

html 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    String basePath = request.getScheme()+"://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath();
%>

<html>
<head>
    <meta charset="utf-8">
</head>
<body>
<h2>Hello World!</h2>

    <form>
        <label for="acc"> </label><input type="text" name="account" id="acc"> <br/>
        <div id="div1"></div>
    </form>


<script type="application/javascript">

    //function  test() { //页面加载后执行function
        var checkButton = document.getElementById("acc");
        //给checkButton绑定onclick
        //checkButton.onclick = function () {
        checkButton.onblur = function () {

            //1. 创建XMLHttpRequest对象(!!!) [ajax引擎对象]
            var xhr = new XMLHttpRequest();
            //   获取用户填写的用户名
            var uname = document.getElementById("acc").value;

            //2. 准备发送指定数据 open, send
            //老师解读
            //(1)"GET" 请求方式可以 GET/POST
            //(2)"/ajax/checkUserServlet?username=" + uname 就是 url
            //(3)true , 表示异步发送
            xhr.open("GET", "<%=basePath%>/verifyAcc?account=" + uname, true);

            //老师说明,在send函数调用前,给XMLHttpRequest 绑定一个事件onreadystatechange
            //该事件表示,可以去指定一个函数,当数据变化,会触发onreadystatechange
            // 每当 xhr对象readyState 改变时,就会触发 onreadystatechange 事件
            xhr.onreadystatechange = function () {
                //如果请求已完成,且响应已就绪, 并且状态码是200
                if (xhr.readyState == 4 && xhr.status == 200) {
                    //把返回的jon数据,显示在div
                    //document.getElementById("div1").innerHTML = xhr.responseText;

                    //console.log("xhr=", xhr)
                    var responseText = xhr.responseText;
                    //console.log("返回的信息=" + responseText);
                    //if (responseText != "") {
                    if (responseText === "f") {
                        //document.getElementById("div1").value = "用户名不可用"
                        document.getElementById("div1").innerHTML = "用户名不可用"
                    } else {
                        //document.getElementById("div1").value = "用户名可用"
                        document.getElementById("div1").innerHTML = "用户名可用"
                    }
                }
            }

            //3. 真正的发送ajax请求[http请求]
            // 老师再说明如果你POST 请求,再send("发送的数据")
            xhr.send();

        };
    //}
</script>
</body>
</html>


<!--
下发代码:
//1. 创建XMLHttpRequest对象(!!!) [ajax引擎对象]
var xhr = new XMLHttpRequest();
//   获取用户填写的用户名
var uname = document.getElementById("acc").value;

//2. 准备发送指定数据 open, send
//老师解读
//(1)"GET" 请求方式可以 GET/POST
//(2)"/ajax/checkUserServlet?username=" + uname 就是 url
//(3)true , 表示异步发送
xhr.open("GET", "<%=basePath%>/verifyAcc?account=" + uname, true);

//老师说明,在send函数调用前,给XMLHttpRequest 绑定一个事件onreadystatechange
//该事件表示,可以去指定一个函数,当数据变化,会触发onreadystatechange
// 每当 xhr对象readyState 改变时,就会触发 onreadystatechange 事件
xhr.onreadystatechange = function () {
    //如果请求已完成,且响应已就绪, 并且状态码是200
    if (xhr.readyState == 4 && xhr.status == 200) {

    }
}

//3. 真正的发送ajax请求[http请求]
// 老师再说明如果你POST 请求,再send("发送的数据")
xhr.send();

-->

2.AjaxController.java

java 复制代码
package zyq.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AjaxController {

    @RequestMapping("/verifyAcc")
    @ResponseBody
    public String testAcc(String account){
        System.out.println(account);
        if("zs".equalsIgnoreCase(account)){
            return "f";
        }else{
            return "t";
        }
    }

}

其他配置文件:

3.applicationContext.xml

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:p="http://www.springframework.org/schema/p"
	   xmlns:aop="http://www.springframework.org/schema/aop"
	   xmlns:mvc="http://www.springframework.org/schema/mvc"
	   xmlns:util="http://www.springframework.org/schema/util"
	   xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jee="http://www.springframework.org/schema/jee"
	xsi:schemaLocation="    
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd  
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd  
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
 

	<context:component-scan base-package="zyq"/>
	<mvc:annotation-driven/>


	<!--   浏览器的地址中写"/static/",最终会访问项目中的/static/文件夹	-->
	<!--   浏览器的地址中写"/static/",最终会访问项目中的/static/文件夹  -->
	<!--设置此静态资源配置后,views中的网页可以直接访问-->
	<mvc:resources mapping="/static/" location="/static/"/>
	<mvc:default-servlet-handler/>

	<!-- 读取db.properties -->
	<!--<util:properties id="dbConfig"  location="classpath:db.properties"/>-->

	<!-- 2.配置数据源(采用dbcp连接池) -->
	<bean id="ds"
		  class="org.apache.commons.dbcp.BasicDataSource">
		<property name="url" value="jdbc:mysql://localhost:3306/test?characterEncoding=utf-8&amp;serverTimezone=GMT%2B8" />
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
		<property name="username" value="root" />
		<property name="password" value="root" />
		<property name="initialSize" value="2" />
		<property name="maxActive" value="10" />
	</bean>

	<!-- 3.配置SqlSessionFactoryBean -->
	<bean class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 指定数据源 -->
		<property name="dataSource" ref="ds" />
	</bean>

	<!-- 4.配置MapperScannerConfigurer -->
	<!--<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">-->
		<!-- 接口文件在哪里 -->
		<!--<property name="basePackage" value="zyq.dao" />
	</bean>-->


</beans>

4.web.xml:

XML 复制代码
  <servlet>
    <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
      <!--  注意:classpath: 和springmvc.xml之间不能有空格  -->
    </init-param>
    <!--  load-on-startup:值为0或者大于0时,表示项目启动时,就加载DispatcherServlet  -->
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

5.pom.xml:

XML 复制代码
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!--  springAOP框架依赖  -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.2</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <!--<dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>-->


        <!-- MyBatis 依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.3.1</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.5.0</version>
        </dependency>

        <!-- mybatis和spring集成依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.2.4</version>
        </dependency>

        <!-- Spring JDBC -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!-- 阿里的连接池 -->
        <!--<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>-->

        <!--tomcat 10之后的版本这样导入servlet-api.jar-->
        <dependency>
            <groupId>jakarta.servlet</groupId>
            <artifactId>jakarta.servlet-api</artifactId>
            <version>5.0.0</version>
            <scope>provided</scope>
        </dependency>

        <!--tomcat 10之前的版本这样导入servlet-api.jar-->
        <!--        <dependency>
                    <groupId>javax.servlet</groupId>
                    <artifactId>javax.servlet-api</artifactId>
                    <version>4.0.1</version>
                </dependency>-->

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>




        <!--jstl-->
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-spec</artifactId>
            <version>1.2.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>


        <!--4月15添加的依赖-->
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20160212</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.7.2</version>
        </dependency>

        <!--  `json-core`是Jackson的一个模块,但在Jackson 2.x版本中,这个模块已经被重命名为jackson-databind。  -->
        <!--<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>json-core</artifactId>
            <version>2.7.2</version>
        </dependency>-->   <!--json-core用jackson-databind替换了-->
        <!--<dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.2</version>
        </dependency>-->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.5</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.2</version>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <!--slf4j-->
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.22</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.22</version>
        </dependency>
        <dependency>
            <groupId>ognl</groupId>
            <artifactId>ognl</artifactId>
            <version>3.1.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.3</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>2.3</version>
        </dependency>

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.21.0-GA</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.4.1</version>
        </dependency>

        <!--<dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.4</version>
        </dependency>-->

        <dependency>
            <groupId>org.apache.ant</groupId>
            <artifactId>ant-launcher</artifactId>
            <version>1.9.6</version>
        </dependency>
        <dependency>
            <groupId>org.ow2.asm</groupId>
            <artifactId>asm</artifactId>
            <version>5.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.9.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>5.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.apache.xbean</groupId>
            <artifactId>xbean-reflect</artifactId>
            <version>3.4</version>
        </dependency>

        <dependency>
            <groupId>com.google.collections</groupId>
            <artifactId>google-collections</artifactId>
            <version>1.0</version>
        </dependency>

6.改进ajax:

将index.jsp中的ajax请求方式改为jQuery发请求

html 复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    String basePath = request.getScheme()+"://" +
            request.getServerName() + ":" + request.getServerPort() +
            request.getContextPath();
%>

<html>
<head>
    <meta charset="utf-8">
    <%--<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>--%>
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
</head>
<body>

    <form>
        <label for="acc">账号:</label><input type="text" name="account" id="acc"> <br/>
        <div id="div1"></div>
    </form>


<script type="application/javascript">
    var checkButton = document.getElementById("acc");
    //给checkButton绑定onclick
    //checkButton.onclick = function () {
    checkButton.onblur = function () {
        var uname = document.getElementById("acc").value;
        $.ajax({
            async: true,
            url: "<%=basePath%>/verifyAcc?account="+uname,
            contentType: 'application/x-www-form-urlencoded;charset=utf-8',
            type: 'GET',
            //data : { "account" : uname },
            dataType: 'text',
            success: successCallback,
            error: errorCallback
        });
    };


    function successCallback (json, status) {
        if (json === "f") {
            document.getElementById("div1").innerHTML = "用户名不可用"
            document.getElementById("div1").style.color="red";
        } else {
            document.getElementById("div1").innerHTML = "用户名可用"
        }
    }

    function errorCallback(xhr, status){
        console.log('出问题了!'+status);
    }
</script>
</body>
</html>

提示:

下发代码:

$.ajax({

async: true,

url: '/url/to/json',

type: 'GET',

data : { id : 123 },

dataType: 'json',

timeout: 30000,

success: successCallback,

error: errorCallback,

complete: completeCallback,

statusCode: {

404: handler404,

500: handler500

}

})

function successCallback(json) {

$('<h1/>').text(json.title).appendTo('body');

}

function errorCallback(xhr, status){

console.log('出问题了!');

}

function completeCallback(xhr, status){

console.log('Ajax请求已结束。');

}

$.ajax({

url:请求地址

type:"get | post | put | delete " 默认是get,

data:请求参数 {"id":"123","pwd":"123456"},

dataType:请求数据类型"html | text | json | xml | script | jsonp ",

success:function(data,dataTextStatus,jqxhr){ },//请求成功时error:function(jqxhr,textStatus,error)//请求失败时

})

相关推荐
王哈哈^_^1 小时前
【数据集】【YOLO】【目标检测】交通事故识别数据集 8939 张,YOLO道路事故目标检测实战训练教程!
前端·人工智能·深度学习·yolo·目标检测·计算机视觉·pyqt
cs_dn_Jie2 小时前
钉钉 H5 微应用 手机端调试
前端·javascript·vue.js·vue·钉钉
开心工作室_kaic2 小时前
ssm068海鲜自助餐厅系统+vue(论文+源码)_kaic
前端·javascript·vue.js
有梦想的刺儿2 小时前
webWorker基本用法
前端·javascript·vue.js
cy玩具3 小时前
点击评论详情,跳到评论页面,携带对象参数写法:
前端
qq_390161773 小时前
防抖函数--应用场景及示例
前端·javascript
John.liu_Test4 小时前
js下载excel示例demo
前端·javascript·excel
Yaml44 小时前
智能化健身房管理:Spring Boot与Vue的创新解决方案
前端·spring boot·后端·mysql·vue·健身房管理
PleaSure乐事4 小时前
【React.js】AntDesignPro左侧菜单栏栏目名称不显示的解决方案
前端·javascript·react.js·前端框架·webstorm·antdesignpro
哟哟耶耶4 小时前
js-将JavaScript对象或值转换为JSON字符串 JSON.stringify(this.SelectDataListCourse)
前端·javascript·json