前后端交互——Ajax

前后端交互——Ajax,第1张

前后端交互Ajax AjaxjQuery中的ajax$.get()$.post()$.ajax() 案例:图书列表

Ajax

Ajax 即“AsynchronousJavascriptAndXML”(异步 JavaScript 和 XML),是指一种创建交互式应用的网页开发技术。通俗的理解就是在网页中利用XMLHttpRequest对象和服务器进行数据交互的方式。

传统的网页(不使用 Ajax)如果需要更新内容,必须重载整个网页页面。其缺点如下:
1. 本身是针对MVC编程,不符合前端MVVM的浪潮
2. 基于原生XHR开发,XHR本身的架构不清晰
3. 不符合关注分离(Separation of Concerns)的原则
4. 配置和调用方式非常混乱,而且基于事件的异步模型不友好。

Ajax典型的应用场景

用户名检测:注册用户时,通过Ajax的方式动态检测用户名是否被占用搜索提示,输入关键字,动态加载数据搜索提示列表数据分页显示数据的增删改查
jQuery中的ajax $.get()

用来发起get请求,从而将服务器上的资源请求到客户端进行使用

$.post()

用来发起post请求,向服务器提交数据

	<button id="btnGET">不带参数的请求button>
    <button id="btnGET1">带参数的请求button>
    <button id="btnPOST">提交数据button>
    <script>
        $(function() {
        //通过get发出不带参数的请求
            $('#btnGET').on('click', function() {
                $.get('http://www.liulongbin.top:3006/api/getbooks', function(res) {
                    console.log(res);
                })
            })
            $('#btnGET1').on('click', function() {
            //通过get发出带参数的请求
                $.get('http://www.liulongbin.top:3006/api/getbooks', {
                    id: 1
                }, function(res) {
                    console.log(res);
                })
            })
            $('#btnPOST').on('click', function() {
            //通过POST提交数据
                $.post('http://www.liulongbin.top:3006/api/addbook', {
                    bookname: '背影',
                    author: '朱自清',
                    publisher: '天津图书出版社'
                }, function(res) {
                    console.log(res)
                })
            })
        })
    script>

$.ajax()

既可以发get请求,也可以发post请求


	//通过Ajax发起GET请求
    $.ajax({
        method: 'GET',
        url: 'http://www.liulongbin.top:3006/api/getbooks',
        data: {
            id: 1313,
        },
        success: function(res) {
            console.log(res);
        }
    })

案例:图书列表

页面搭建结构

DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Documenttitle>
    <link rel="stylesheet" href="./lib/bootstrap.css">
    <script src="./lib/jquery.js">script>
    <script src="./js/index.js">script>
    <style>
        body {
            padding: 20px;
        }
    style>
head>

<body>
    


    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">添加新图书h3>
        div>
        <div class="panel-body form-inline">
            <div class="input-group">
                <div class="input-group-addon">书名div>
                <input type="text" class="form-control" id="iptBookname" placeholder="请输入书名">
            div>
            <div class="input-group">
                <div class="input-group-addon">作者div>
                <input type="text" class="form-control" id="iptAuthor" placeholder="请输入作者">
            div>
            <div class="input-group">
                <div class="input-group-addon">出版社div>
                <input type="text" class="form-control" id="iptPublisher" placeholder="请输入出版社">
            div>
            <button id="btnAdd" class="btn btn-primary">添加button>
        div>
    div>


    

    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>IDth>
                <th>书名th>
                <th>作者th>
                <th>出版社th>
                <th> *** 作th>
            tr>
        thead>
        <tbody id="tb">

        tbody>
    table>

body>

html>

核心代码
1. 获取图书列表

// 获取图书数据
    function getBookList() {
        // 发起ajax请求获取图书列表
        $.get('http://www.liulongbin.top:3006/api/getbooks', function(res) {
            console.log(res); //获取列表是否成功

            if (res.status != 200) return alert('获取数据失败')

            // 渲染页面结构
            var rows = []
            $.each(res.data, function(i, item) { //循环数组

                // 循环拼接字符串
                rows.push('' + item.id + '' + item.bookname + '' + item.author + '' + item.publisher + ' + item.id + '">删除')
            })

            //渲染表格结构,清空在追加
            $('#tb').empty().append(rows.join(''))
        })
    }
    getBookList()

2.删除图书

// 删除图书,需要通过代理方式为动态添加的元素绑定点击事件!!
    $('tbody').on('click', '.del', function() {
        console.log(1);
        // 获取删除图书的id
        var id = $(this).attr('data-id')
        console.log(id);
        // 发起ajax,根据id删除相应的图书
        $.get('http://www.liulongbin.top:3006/api/delbook', { id: id }, function(res) {
            if (res.status !== 200) return alert('删除图书失败');
            // 删除成功,重新加载图书列表
            getBookList()
        })

    })

3.添加图书

 $('#btnAdd').on('click', function() {

        var bookname = $('#iptBookname').val()
        var author = $('#iptAuthor').val()
        var publisher = $('#iptPublisher').val()
            // 判断是否为空
        if (bookname.length <= 0 || author.length <= 0 || publisher.length <= 0) return alert('请填写完整的图书信息')
        $.post('http://www.liulongbin.top:3006/api/addbook', { bookname: bookname, author: author, publisher: publisher }, function(res) {
            if (res.status !== 201) return alert('添加图书失败')
            getBookList()
            $('#iptBookname').val()
            $('#iptAuthor').val()
            $('#iptPublisher').val()
        })
    })

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1297585.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存