ajax有關(guān)json的處理
json 要求返回的數(shù)據(jù)類型必須時(shí)json格式數(shù)據(jù)
注意,在python中如果直接返回列表,在ajax中寫了第四個(gè)參數(shù)json后,會(huì)自動(dòng)轉(zhuǎn)成js中的數(shù)組
-*- coding: utf-8 -*-
import cgi,cgitb,time
cgitb.enable()
print("Content-Type: text/html;charset: utf-8") # HTML is following
print() # blank line, end of headers
arr = [1,2,3,4]
print(arr)
在python中直接返回字典或字符串.數(shù)字,那么當(dāng)前ajax會(huì)認(rèn)為不是json格式數(shù)據(jù),那么就認(rèn)為當(dāng)前ajax請(qǐng)求失敗,如果要求json格式,那么在python返回?cái)?shù)據(jù)使用 使用json.dumps(),轉(zhuǎn)完返回
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import cgi,cgitb,json
cgitb.enable()
print("Content-Type: text/html") # HTML is following
print() # blank line, end of headers
# 返回?cái)?shù)據(jù)類型
# arr = {'a':'abc','b':'bbc','c':'ccc'}
arr = [
{'a':'abc','b':'bbc','c':'ccc'},
{'a':'abc','b':'bbc','c':'ccc'},
{'a':'abc','b':'bbc','c':'ccc'},
{'a':'abc','b':'bbc','c':'ccc'},
]
# print(type(arr))
print(json.dumps(arr))
如果返回的數(shù)據(jù)時(shí)json格式,那么不光能接收到數(shù)據(jù),而且自動(dòng)使用eval轉(zhuǎn)換

有關(guān)dumps的操作
import json
# json.dumps()函數(shù)的使用,將字典轉(zhuǎn)化為字符串
dict1 = {"age": "12"}
json_info = json.dumps(dict1)
print("dict1的類型:"+str(type(dict1)))
print("通過json.dumps()函數(shù)處理:")
print("json_info的類型:"+str(type(json_info)))