Ajax怎么用,异步如何实现

ajax怎么用

Posted by LY on October 31, 2018

欢迎大家关注我的以下主页,尤其是今日头条!!!谢谢🙏🙏🙏

csdn:雷园的csdn博客

个人博客:雷园的个人博客

简书:雷园的简书

今日头条:来自底层程序员的仰望

Ajax怎么用

首先我们从jsp或者是html文件开始

1.导入jQuery包,可以选择通过网络地址进行导入 ,也可以下载jQuery的js文件进行导入,两种方法如下。

// 在线引用
<script src="http://code.jquery.com/jquery-1.4.1.min.js"></script>
// 线下引用
<script src="/{你的js文件路径}/jquery-1.4.1.min.js"></script>

2.编写我们的ajax异步方法。

// 1.首先编写触发方法的事件,这里我以点击按钮为例(也可以是onKeyUp()、onChange()、等等)
<input type="button" value="点击登录" onclick="testMyAjax()"/>
// 2.编写我们的testMyAjax()方法
<script>
    function testMyAjax() {
        $.ajax({
            type: "post", // 提交方式
            // 返回数据类型,*注意如果返回值为String类型则需要去掉此条
            dataType: "json", 
            url: "/test/testMyAjax", // 访问路径
            data: { // 提交数据
                "username": "admin", // 前者为字段名,后者为数据
                "password": "admin"
            },
            success(data) { // 成功调用的回调函数
                alert(data);
            },
            error() { // 调用失败
                alert("ajax出错,未能成功访问路径");
            }
        })
    }
</script>

接下来我们编写后台的Java代码

1.导入SpringMVC相关jar包文件,如果试用Maven做依赖管理的话,可以直接在pom.xml中插入以下代码。Maven+SSM:Spring、SpringMVC、Mybatis项目整合

<!-- 这里只列出Springmvc相关依赖,其他的请仔细阅读我的另一篇博客👆 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>4.3.1.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.1.RELEASE</version>
</dependency>

2.开始编写我们的TestController代码。

package controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping("/test")
public class TestController {
    @RequestMapping(value = "/testMyAjax", method = RequestMethod.POST)
    @ResponseBody // 这里意为返回数据将Json类型数据
    public String testMyAjax(@RequestParam("username") String username, @RequestParam("password") String password) {
        if ("admin".equals(username) && "admin".equals(password)) {
            return "用户名密码正确,登陆成功!";
        } else {
            return "用户名密码错误,登陆失败!!!";
        }
    }
}

3.接下来就是运行我们的程序,进入html或者jsp点击按钮即可看到效果,我这里就不做演示,大家如果还有什么问题的话随时留言。