JSONP 装饰器允许将标准application/json
响应作为参数中定义的 Javascript 函数返回callback
。
在这种情况下,我使用 JsonResponse(HttpResponse 的子类)并且if
条件导致函数返回原始响应而不是 JSONP 格式的响应。我会说这是因为simplejson
解析器与HttpResponse
对象不兼容。
问题是如何使其兼容JsonResponse
?
JSON响应https://www.domain.com/data.json
:
{“文档”:“546546545”,“订单”:“98745”,“无”:“0.0”}
JSONP 响应https://www.domain.com/data.json?callback=jQuery111305146260466426611_1448872734459
:
jQuery111305146260466426611_1448872734459({"doc": "546546545", "order": "98745", "nothing": "0.0"});
视图.py:
from django.http import JsonResponse
from collections import OrderedDict
from polls.jsonp_decorator import json_response
@json_response
def sampledata(request):
data = OrderedDict([('doc', '546546545'), ('order', '98745'), ('nothing', '0.0')])
return JsonResponse(data)
jsonp_decorator.py:
from django.http import HttpResponse
import simplejson
def json_response(func):
def decorator(request, *args, **kwargs):
objects = func(request, *args, **kwargs)
if isinstance(objects, HttpResponse): #here it returns objects
return objects
try:
data = simplejson.dumps(objects)
if 'callback' in request.REQUEST:
# A jsonp response!
data = '%s(%s);' % (request.REQUEST['callback'], data)
return HttpResponse(data, 'text/javascript; charset=utf-8')
except:
data = simplejson.dumps(str(objects))
return HttpResponse(data, 'application/json; charset=utf-8')
return decorator