问题描述
我正在使用 JSONP 将数据从otherdomain.com
发送到mydomain.com
I'm using JSONP to send data from otherdomain.com
to mydomain.com
但是,当我尝试在django控制器中解析JSONP数据(views.py
)时,我会犯错.
However, I got errer when I tried to parse JSONP data in django controller (views.py
).
这是我的代码.
mydomain.com
客户端页面中的Javascript
Javascript in mydomain.com
client page
jsonData = {
'foo': 'bar',
}
$.ajax({
url: 'http://otherdomain.com/end_point/',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: jsonData,
dataType : 'jsonp',
jsonp : 'callback'
});
mydomain.com
from django.http import JsonResponse
import json
def decode_jsonp(request):
if 'callback' in request.GET:
json_object = json.loads(request.body) # Raise error
json_object = json.dumps(request.body) # Do not raise error but returns nothing
json_object = json.loads(json.dumps(request.body)) # Raise error
foo = json_object['foo']
return JsonResponse({'foo': foo})
我不知道应该用什么代替json_object = json.loads(request.body)
I don't know what should I substitue for json_object = json.loads(request.body)
推荐答案
JSONP对象在其周围带有括号和一个回调.但是Python的json
模块无法识别JSONP对象.因此,您必须首先通过删除周围的括号和回调名称将其转换为JSON对象.
A JSONP object has parentheses around it and a callback. But Python's json
module doesn't recognise a JSONP object. So, you'll have to first convert it to JSON object by removing the surrounding parentheses and the callback name.
示例
>>> data = 'callback({"key": "val"})' # a common JSONP object
>>>
>>> json.loads(data)
# raises ValueError
>>>
>>> data_json = data.split("(", 1)[1].strip(")") # convert to json
>>> data_json
'{"key": "val"}'
>>>
>>> json.loads(data_json)
# success
这篇关于Django-解析JSONP(带有填充的Json)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!