1.数据交换格式
服务端返回的数据,在本质上都是字符串,只是原生Ajax 或jQuery Ajax将这些字符串转换为容易理解的各种常用格式。
a. Text
文本字符串
b. XML
JavaScript中特殊的对象
c. JSON
JavaScript中JSON值数组、字典
d. Script
通过eval将字符串当做javaScript代码执行 eval("alert(123);")
2.原生Ajax
text:
xhr.responseText
xml:
xhr.responseXML
json:
JSON.parse(xhr.responseText)
script:
eval(xhr.responseText)
3.jQuery Ajax
text:
dataType:'text'
xml:
dataType:'xml'
json:
dataType:'json'
script:
dataType:'script'
jQuery Ajax 四种格式转换实例
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>
测试结果:
***微信扫一扫,关注“python测试开发圈”,了解更多测试教程!***