在网页访问中通过HTTP协议中的get/post文件发送数据或请求。在浏览器中输入url后,浏览器就会帮助我们完成请求的发送和返回,并刷新更新界面。但是,如果我们不想更新界面,仅仅是发送一个get/post文件数据(请求)传给服务器,然后获取服务器返回的response文件,这时就可以用ajax技术实现。
实现ajax的方法:1)采用原生的javascript发送,比较麻烦;2)使用jquery封装好了ajax方法
views.py视图函数,编写逻辑代码
1 from django.shortcuts import render 2 from django.http import HttpResponse 3 import json 4 # Create your views here. 5 6 7 # def index(request): 8 # lists = ['a', 'b', 'c'] 9 # dicts = {'a': 'apple', 'b': 'banana'} 10 # 11 # return render(request, 'home.html', { 12 # 'lists': json.dumps(lists), 13 # 'dicts': json.dumps(dicts), 14 # }) 15 def index(request): 16 return render(request, 'home.html') 17 18 19 def add(request): 20 a = request.GET['a'] 21 b = request.GET['b'] 22 c = int(a)+int(b) 23 return HttpResponse(str(c)) 24 25 # def add(request): 26 # a = request.GET['a'] 27 # b = request.GET['b'] 28 # c = int(a)+int(b) 29 # return_json = {"result": c} 30 # return HttpResponse(json.dumps(return_json), content_type='application/json')
home.html访问页面
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form action="/add/" method="get"> 9 10 a:<input type="text" name="a" id="a"><br> 11 b:<input type="text" name="b" id="b"><br> 12 <p>result:<span id="result"></span></p> 13 <button type="button" id="sum">Calc</button> 14 </form> 15 16 <script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.min.js"></script> 17 <script> 18 $(document).ready(function () { 19 $("#sum").click(function () { 20 var a = $('#a').val(); 21 var b = $('#b').val(); 22 23 $.get("/add/", {'a':a, 'b':b}, function (ret) { 24 $("#result").html(ret) 25 }) 26 }); 27 }); 28 </script> 29 </body> 30 </html>
urls.py进行地址映射
1 """my_query URL Configuration 2 3 The `urlpatterns` list routes URLs to views. For more information please see: 4 https://docs.djangoproject.com/en/dev/topics/http/urls/ 5 Examples: 6 Function views 7 1. Add an import: from my_app import views 8 2. Add a URL to urlpatterns: path('', views.home, name='home') 9 Class-based views 10 1. Add an import: from other_app.views import Home 11 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') 12 Including another URLconf 13 1. Import the include() function: from django.urls import include, path 14 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) 15 """ 16 from django.contrib import admin 17 from django.urls import path 18 from blog import views 19 20 urlpatterns = [ 21 path('admin/', admin.site.urls), 22 path('index/', views.index), 23 path('add/', views.add), 24 ]
参考:http://blog.csdn.net/autoliuweijie/article/details/50291357