Ajax(js)

Ajax用js实现只有两种方式:get,post

AJAXAsynchronous Javascript And XML)翻译成中文就是异步JavascriptXML”。即使用Javascript语言与服务器进行异步交互,传输的数据为XML(当然,传输的数据不只是XML)。

  • 同步交互:客户端发出一个请求后,需要等待服务器响应结束后,才能发出第二个请求;
  • 异步交互:客户端发出一个请求后,无需等待服务器响应结束,就可以发出第二个请求。

AJAX除了异步的特点外,还有一个就是:浏览器页面局部刷新;(这一特点给用户的感受是在不知不觉中完成请求和响应过程)

 

 

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); //参数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); #参数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")
 

 

posted @ 2018-05-13 20:45  MISF  阅读(223)  评论(0编辑  收藏  举报
     JS过度和变形效果演示   
  
    html5.png