Python - Django - jQuery achieve a simple AJAX

AJAX partial refresh instance:

Basic transmission using jQuery AJAX request

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)

Visit, http: //127.0.0.1: 8000 / index /

 

 Enter the number of groups, click on the "AJAX Submit" page does not refresh will calculate the results

 

Example AJAX the code analysis:

 

<button id = "b1"> AJAX Test </ Button> 
<Script> 
  $ ( "# b1") the Click (function () {# b1 if the id is the button is clicked. 
    $ .ajax ({ 
      URL: "/ ajax_add / ", URL # ajax requested data 
      type:" GET ", mode # requested 
      data: {" i1 ": $ (" # i1 ") i2 val (),." ": $ (" # i2 "). val ()}, to be transmitted to data # 
      success: function (data) {# request is processed normally if the function is executed 
        . $ ( "# i3") val (data); # fill the data returned from the rear end to in i3 
      } 
    }) 
  }) 
</ Script>

 

Guess you like

Origin www.cnblogs.com/sch01ar/p/11443000.html