服務端返回的數據,在本質上都是字符串,只是原生Ajax 或jQuery Ajax將這些字符串轉換爲容易理解的各類經常使用格式。javascript
a. Textcss
文本字符串html
b. XMLjava
JavaScript中特殊的對象python
c. JSONjquery
JavaScript中JSON值數組、字典ajax
d. Scriptdjango
經過eval將字符串當作javaScript代碼執行 eval("alert(123);")json
text:數組
xhr.responseText
xml:
xhr.responseXML
json:
JSON.parse(xhr.responseText)
script:
eval(xhr.responseText)
text:
dataType:'text'
xml:
dataType:'xml'
json:
dataType:'json'
script:
dataType:'script'
url.py
from django.conf.urls import url from hello import views urlpatterns = [ url(r'resp_type/', views.resp_type, name='resp_type'), url(r'resp_text/', views.resp_text, name='resp_text'), url(r'resp_xml/', views.resp_xml, name='resp_xml'), url(r'resp_json/', views.resp_json, name='resp_json'), url(r'resp_script/', views.resp_script, name='resp_script'), ]
views.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt def resp_type(request): return render(request, 'resp_type.html') @csrf_exempt def resp_text(request): content = "Hello World!" return HttpResponse(content) @csrf_exempt def resp_xml(request): content = """ <note> <to>George</to> <from>John</from> <heading>Reminder</heading> <body>Don't forget the meeting!</body> </note> """ # 默認響應內容是 text/html;charset=utf-8 response = HttpResponse(content, content_type='application/xml;charset=utf-8') response.status_code = 200 return response @csrf_exempt def resp_json(request): content = '{"name":"Milton","age":18}' return HttpResponse(content) @csrf_exempt def resp_script(request): content = "alert(123);" return HttpResponse(content)
resp_type.html:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Ajax數據交換格式</title> </head> <body> <h1>jQuery-Ajax數據交換格式</h1> <input type="button" onclick="RespText();" value="響應text字符串"> <input type="button" onclick="RespXml();" value="響應xml字符串"> <input type="button" onclick="RespJson();" value="響應json字符串"> <input type="button" onclick="RespScript();" value="響應script字符串"> <script src="http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script> <script type="text/javascript"> function RespText() { $.ajax({ url: {% url 'resp_text' %}, dataType: 'text', success: function (data, statusText, xmlHttpRequest) { console.log(data); } }); } function RespXml() { $.ajax({ url: {% url 'resp_xml' %}, dataType: 'xml', success: function (data, statusText, xmlHttpRequest) { console.log(data); }, error: function (xmlHttpRequest, statusText, errorThrown) { console.log(statusText); } }); } function RespJson() { $.ajax({ url: {% url 'resp_json' %}, dataType: 'json', success: function (data, statusText, xmlHttpRequest) { console.log(data); } }); } function RespScript() { $.ajax({ url: {% url 'resp_script' %}, dataType: 'script', success: function (data, statusText, xmlHttpRequest) { console.log(data); } }); } </script> </body> </html>
測試結果: