Python - Django - jQuery 实现简单的 AJAX

AJAX 局部刷新实例:

使用 jQuery 实现基本的发送 AJAX 请求

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title> ajax 局部刷新实例 </title>
</head>
<body>

<input type="text" id="i1">+
<input type="text" id="i2">=
<input type="text" id="i3">
<input type="button" value="AJAX提交" id="b1">

<script src="/static/jquery-3.3.1.js"></script>
<script>
  $("#b1").on("click", function () {
    $.ajax({
      url:"/ajax_add/",
      type:"GET",
      data:{"i1":$("#i1").val(),"i2":$("#i2").val()},
      success:function (data) {
        $("#i3").val(data);
      }
    })
  })
</script>

</body>
</html>

 urls.py:

from django.conf.urls import url
from app01 import views


urlpatterns = [
    url(r'^index/', views.index),
    url(r'^ajax_add/', views.ajax_add),
]

views.py:

from django.shortcuts import render, HttpResponse


def index(request):
    return render(request, "index.html")


def ajax_add(request):
    num1 = request.GET.get("i1")
    num2 = request.GET.get("i2")
    ret = int(num1) + int(num2)
    return HttpResponse(ret)

访问,http://127.0.0.1:8000/index/

 

 输入两组数,点击 “AJAX提交”,页面没有刷新也会计算出结果

 

上例 AJAX 代码解析:

<button id="b1">AJAX 测试</button>
<script>
  $("#b1").click(function () {  # 如果 id 为 b1 的按钮被点击
    $.ajax({
      url: "/ajax_add/",   # ajax 数据请求的 URL
      type: "GET",         # 请求的方式
      data:{"i1":$("#i1").val(),"i2":$("#i2").val()},  # 要发送的数据
      success: function (data) {   # 如果请求被正常处理就执行该函数
        $("#i3").val(data);  # 把从后端返回的数据填到 i3 中
      }
    })
  })
</script>

 

Ajax 实现 url 跳转:

index.html:

<button id="b2">跳转</button>

<script src="/static/jquery-3.3.1.js"></script>
<script>
    $("#b2").on("click", function () {
        $.ajax({
            url: "/ajax_test/",
            type: "GET",
            success: function (url) {
                location.href = url;  # url 跳转
            }
        })
    })
</script>

views.py:

from django.shortcuts import render, HttpResponse


def ajax_test(request):
    return HttpResponse("https://www.cnblogs.com/sch01ar/")

访问,http://127.0.0.1:8000/index/

 

 点击“跳转”,就会跳转到博客园 https://www.cnblogs.com/sch01ar/

 

Ajax 显示图片:

index.html:

<button id="b3">显示图片</button>

<script src="/static/jquery-3.3.1.js"></script>
<script>
    $("#b3").on("click", function () {
        $.ajax({
            url: "/ajax_test/",
            type: "GET",
            success: function (img_url) {
                var imgEle = document.createElement("img");
                imgEle.src = img_url;
                $("#b3").after(imgEle);
            }
        })
    })
</script>

views.py:

from django.shortcuts import render, HttpResponse


def ajax_test(request):
    img_url = "https://www.cnblogs.com/sch01ar/0.jpg"
    return HttpResponse(img_url)

访问,http://127.0.0.1:8000/index/

 

点击 “显示图片”

 

posted @ 2019-09-01 17:48  Sch01aR#  阅读(574)  评论(0编辑  收藏  举报