Ajax(js)

1.get请求

####index.html#####
<
button onclick="fun1()">ajax1</button> <script> function fun1(){ function createXMLhttpRequest(){ //Ajax在js中,要区别浏览器的版本 var xmlHttp; try{ xmlHttp=new XMLHttpRequest(); }catch (e){ try { xmlHttp=new ActiveXObject("Msxm12.XMLHTTP"); }catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){} } } return xmlHttp; } // 1.新建对象 var xmlHttp=createXMLhttpRequest(); //4.设置监听(建议写在这个位置) xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4 && xmlHttp.status==200){ //固定写法,一旦服务端发来信息,就打印 alert(xmlHttp.responseText); //xmlHttp.responseText接受服务器发送过来的Httpresponse对象..结果为hello boy } }; // 2.打开url xmlHttp.open("GET","/ajax_get/",true); //3.发送数据给服务端 xmlHttp.send(null); } </script>


####后端views.py#####
def index(req):
return render(req,"index.html")
def ajax_get(req):
return HttpResponse("hello boy")



######后端urls.py#####
path('admin/', admin.site.urls),
path('index/',views.index),
 

2.post请求

#####input.html######
<
form action=""> <p><input type="text" name="username" onblur="fun2(this) "> <span id="getusername"></span></p> <p><input type="password" name="password"> <span id="getpassword"></span></p> <p><input type="submit"></p> </form> <script> function fun2(self){ var username=self.value; #获取input标签的值 function createXMLhttpRequest(){ var xmlHttp; try{ xmlHttp=new XMLHttpRequest(); }catch (e){ try { xmlHttp=new ActiveXObject("Msxm12.XMLHTTP"); }catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }catch (e){} } } return xmlHttp; } var xmlHttp=createXMLhttpRequest(); xmlHttp.onreadystatechange=function(){ if(xmlHttp.readyState==4 && xmlHttp.status==200){ if (xmlHttp.responseText=="0"){ #如果后端返回的值为0 var getusername=document.getElementById("getusername"); getusername.innerHTML="用户不存在"; } } }; xmlHttp.open("POST","/form_get1/",true); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xmlHttp.send("username="+username); #注意发送的参数 } </script>


###后端urls.py####
path('form_get/',views.form_get),
path('form_get/',views.form_get),

###后端views.py####
def form_get(req):
return render(req,"input.html")
def form_get1(req):
if req.method=="POST":
if req.POST.get("username")=="kkk": #前端中send中的username
return HttpResponse("1")
return HttpResponse("0")
 

猜你喜欢

转载自www.cnblogs.com/gaoyukun/p/9033263.html
今日推荐