iframe實現偽ajax
阿新 • • 發佈:2019-03-10
for target render inpu 技術分享 json數據 request end 數據返回
iframe實現偽ajax
數據提交的兩種方式:
Form Ajax
Ajax提交數據的方法:
JS實現 Jquery “偽”Ajax
"偽"Ajax:
iframe+from實現
示例程序:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {% load staticfiles %} <style> </style> </head> <body> <!--window.location,reload--> <script src="{% static ‘/js/jquery/jquery-3.3.1.js‘ %}"></script> <!--引入jquery庫。必須放在js文件最前面,避免子模板出現$is not defined問題--> <iframe id="iframe" name="ifra" ></iframe> <form id="fm" method="POST" action="/ajax.html/" target="ifra"> {% csrf_token %} <p>用戶名:<input type="text" name="user" ></p> <p>密碼:<input type="password" name="password"></p> <a onclick="ajaxsubmit();">提交</a> </form> <script> <!--#當點擊a標簽的時候給iframe標簽綁定onload事件,這時不需要傳遞this參數--> <!--this把iframe標簽本身傳進去--> <!--onload為當數據返回回來自動執行--> function ajaxsubmit(){ document.getElementById(‘iframe‘).onload=reloadIframe; document.getElementById(‘fm‘).submit(); } function reloadIframe() { <!--#此時this =當前標簽--> console.log(this); console.log(this.contentWindow.document.body.innerHTML); <!--this.contentWindow是進入了另一個html文檔--> <!--this.contentWindow.document.body拿到另一個文檔的body元素--> <!--this.contentWindow.document.body.innerHTML拿到另一個body元素下的HTML內容--> var content=console.log($(this).contents().find(‘body‘).html()); <!--var obj=JSON.parse(content);--> } </script> </body> </html>
分析:
1."偽"Ajax使用from與iframe實現,註意iframe的name屬性和from的target屬性的值相同。 2.這裏給a標簽進行綁定事件,在a標簽的事件裏給iframe標簽綁定事件。 3.iframe綁定的事件為onload,當服務端返回數據的時候,事件才會執行。 4.reloadIframe為iframe的事件函數,當數據返回,肯定要從iframe標簽下拿到返回的數據。 5.這裏this指當前標簽,為iframe標簽,註意,不需要人為傳遞this,如果綁定事件的方式為onload="reloadIframe(this);" function reloadIframe{//具體代碼};則需要傳遞this6.獲取iframe裏服務端返回的數據: 普通方法:this.contentWindow.document.body.innerHTML Jquery:$(this).contents().find(‘body‘).html() 7.如果是json數據,需要進行反序列化 JSON.parse(content) 註意:這裏為post的方式,get方式:method="GET"
視圖函數:
def ajax(request): v1=request.POST v2=request.GET print(v1) print(v2) if request.method=="POST": return HttpResponse(v1[‘user‘]+v1[‘password‘]) else:return render(request,"ajax.html")
iframe實現偽ajax