原生Ajax:
urls.py:
url(r'^ajax/$', views.ajax), url(r'^ajax_json/$', views.ajax_json),
views.py:
def ajax(request): return render(request, 'ajax.html') def ajax_json(request): ret = { 'status': True, 'data': None, } import json return HttpResponse(json.dumps(ret))
ajax.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text"/> <input type="button" value="Ajax1" οnclick="Ajax1();"/> <script> function Ajax1(){ var xhr = new XMLHttpRequest(); xhr.open('GET', '/ajax_json/', true); xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ //4表示接收完毕 var obj = JSON.parse(xhr.responseText); console.log(obj); } }; xhr.setRequestHeader('k1', 'v1'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); xhr.send('name=root;pwd=123'); } </script> </body> </html>
伪ajax:
先了解下iframe标签:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="text" id="url"/><input type="button" value="发送iframe请求" οnclick="iframeRequest();"/> <iframe id="ifm" src="http://www.baidu.com"></iframe> <script type="text/javascript" src="/static/jquery-1.12.4.js"></script> <script> function iframeRequest(){ var url = $('#url').val(); $('#ifm').attr('src', url); } </script> </body> </html>
利用iframe的特性伪造ajax:
<form action="/ajax_json/" method="POST" target="ifm1"> {% csrf_token %} <iframe name="ifm1"></iframe> <input type="text" name="username"/> <input type="text" name="email"/> <input type="submit" value="提交"/> </form>
获取内容:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/ajax_json/" method="POST" target="ifm1"> {% csrf_token %} <iframe id="ifm1" name="ifm1"></iframe> <input type="text" name="username"/> <input type="text" name="email"/> <input type="submit" value="提交" οnclick="submitForm();"/> </form> <script type="text/javascript" src="/static/jquery-1.12.4.js"></script> <script> function submitForm(){ $('#ifm1').load(function(){ var text = $('#ifm1').contents().find('body').text(); var obj = JSON.parse(text); console.log(obj) }) } </script> </body> </html>