Django Ajax - js 1
js实现最简单的Ajax
urls.py
"""Ajax_lesson URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), path('ajax_receive/', views.ajax_receive), ]
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")
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>index</title> </head> <body> <button onclick="func()" >ajax提交</button> </body> <script src="/static/js/ajaxJs.js"></script> </html>
ajaxJs.js
function createXMLHttpRequest() { var xmlHttp; try { xmlHttp=new XMLHttpRequest(); } catch (e){ try { xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") }catch (e){} } } return xmlHttp; } function func() { //1. 创建XMLHttpRequest var xmlhttp = createXMLHttpRequest(); //2. 创建连接 // xmlhttp.open("GET","/ajax_receive/",true); xmlhttp.open("POST","/ajax_receive/",true); //设置请求头,当请求方式是POST方式的时候,不设置请求头后台接收不到数据 xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //3.发送数据 // xmlhttp.send(null); xmlhttp.send("name=xiaoxiao"); //4.监听 xmlhttp.onreadystatechange=function () { // alert(xmlhttp.readyState) if(xmlhttp.readyState==4 && xmlhttp.status ==200){ var data = xmlhttp.responseText alert(data) } }; }
posted on 2018-08-10 10:39 gaizhongfeng 阅读(197) 评论(0) 编辑 收藏 举报