Ajax学习
Ajax,不刷新
实例:任务管理
准备:


案例1(dom方式,发送get请求)



案例1效果:


task_list {% extends 'layout.html' %} {% block title %} <title>任务列表</title> {% endblock %} {% block content %} <div class="container"> <h1>任务管理</h1> <h3>示例1</h3> <input type="button" class="btn btn-primary" value="点击1" onclick="clickMe();"> </div> {% endblock %} {% block js %} <script type="text/javascript"> {# dom 方式#} function clickMe() { {#console.log("提交到了前端控制台")#} $.ajax({ url: '/task/ajax', type: "get", data: { n1: 123, n2: 456 }, {#请求成功后,执行的函数#} success: function (res) { console.log(res) } } ) } </script> {% endblock %}
dom方式,发送POST请求


案例2(jQuery方式,发送请求)


{% extends 'layout.html' %} {% block title %} <title>任务列表</title> {% endblock %} {% block content %} <div class="container"> <h1>任务管理</h1> <h3>示例1</h3> <input type="button" class="btn btn-primary" value="点击1" id="btn1"> </div> {% endblock %} {% block js %} <script type="text/javascript"> $(function () { //页面框架加载完成后代码自动执行 bindBtn1Event(); }) function bindBtn1Event(){ $("#btn1").click(function () { $.ajax({ url: '/task/ajax', type: "post", data: { n1: 123, n2: 456 }, {#请求成功后,执行的函数#} success: function (res) { console.log(res) } } ) }) } </script> {% endblock %}
ajax请求的返回值:一般都是JSON格式



案例3:通过ajax提交数据到后台





{% extends 'layout.html' %} {% block title %} <title>任务列表</title> {% endblock %} {% block content %} <div class="container"> <h1>任务管理</h1> <h3>示例1</h3> <input type="button" class="btn btn-primary" value="点击1" id="btn1"> <h3>实例2</h3> <input type="text" id="txtUser" placeholder="姓名"> <input type="text" id="txtAge" placeholder="年龄"> <input id="btn2" type="button" class="btn btn-primary" value="点击2"> <h3>实例3</h3> <form id="form3"> <input type="text" name="User" placeholder="姓名"> <input type="text" name="Age" placeholder="年龄"> <input type="text" name="Email" placeholder="邮箱"> <input type="text" name="More" placeholder="介绍"> <input id="btn3" type="button" class="btn btn-primary" value="点击3"> </form> </div> {% endblock %} {% block js %} <script type="text/javascript"> $(function () { //页面框架加载完成后代码自动执行 bindBtn1Event(); bindBtn2Event(); bindBtn3Event(); }) function bindBtn1Event() { $("#btn1").click(function () { $.ajax({ url: '/task/ajax', type: "post", data: { n1: 123, n2: 456 }, {#请求成功后,执行的函数#} dataType: "JSON", success: function (res) { console.log(res); console.log(res.status); console.log(res.data); } } ) }) } function bindBtn2Event() { $("#btn2").click(function () { $.ajax({ url: '/task/ajax', type: "post", data: { name: $("#txtUser").val(), age: $("#txtAge").val(), }, {#请求成功后,执行的函数#} dataType: "JSON", success: function (res) { console.log(res); console.log(res.status); console.log(res.data); } } ) }) } function bindBtn3Event() { $("#btn3").click(function () { $.ajax({ url: '/task/ajax', type: "post", data: $("#form3").serialize(), {#请求成功后,执行的函数#} dataType: "JSON", success: function (res) { console.log(res); console.log(res.status); console.log(res.data); } } ) }) } </script> {% endblock %}

浙公网安备 33010602011771号