小生博客:http://xsboke.blog.51cto.com
-------谢谢您的参考,如有疑问,欢迎交流
一. ajax的实现操作流程
实例对象:
var xmlhttp = XMLHttprequest()
连接server端:
xmlhttp.open("")
发送数据:
xmlhttp.send("") # 请求体的内容 ,如果是GET请求就没有内容,内容在URL里面,写为send(null)
监听:
xmlhttp(if == 4:{var context = xmlhttp.responsetext}) # 判断服务器是否响应结束,其中4状态表示服务器响应结束
二. ajax第一样例,发送get请求
2.1 django的urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from ajax import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^index',views.index),
url(r'ajax_receive',views.ajax_receive),
]
2.2 django的views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
def index(req):
return render(req,"index.html")
def ajax_receive(req):
return HttpResponse("hello")
2.3 模板文件 index.html
Title
三. ajax第二样例,发送post请求
3.1 django的urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from ajax import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^index',views.index),
url(r'ajax_receive',views.ajax_receive),
]
3.2 django的views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
def index(req):
return render(req,"index.html")
def ajax_receive(req):
if req.method == "POST":
print("req.POST",req.POST)
return HttpResponse("hello2")
3.3 模板文件 index.html
Title
3.4 GET与POST的不同
3.4.1 open方法改为了POST
3.4.2 需要提交的数据写到send里面
3.4.3 因为POST的Request体是有数据的,所以必须设置请求头
四. AJAX第三例(实现用户名是否已注册)
4.1 功能介绍
在注册表单中,当用户填写了用户名后,把光标移开,会自动向服务器发送异步请求,服务器返回TRUE或False,
返回true表示这个用户已经被注册过,返回false表示没有注册过
客户端得到服务器返回的结果后,确定是否在用户名文本框后显示"用户名已被注册"的错误信息!
4.2 案例分析
- 页面中给出注册表单
- 在username表单字段中添加onblur事件,调用send()方法
- send()方法获取username表单字段的内容,向服务器发送异步请求,参数为username
- django的视图函数:获取username参数,判断是否为"yuan",如果是响应true,否则响应false
4.3 代码
4.3.1 django的urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from ajax import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'ajax_register',views.ajax_register),
]
4.3.2 django的views.py
from django.shortcuts import render,HttpResponse
# Create your views here.
def ajax_register(req):
if req.method == "POST":
username = req.POST.get("username")
if username == "dashan":
return HttpResponse("true")
return HttpResponse("false")
return render(req,"register.html")
4.3.3 模板文件 register.html
Title