我将Django视图中的JSON字符串发送到客户端名为idbop.js
的javascript文件。我在Django中使用序列化程序将Django中的查询结果转换为JSON。这是我在Django的views.py中的代码
def index(request):
template='posts/index.html'
results=feed.objects.all()
jsondata = serializers.serialize('json',results)
context={
'results':results,
'jsondata':jsondata,
}
return render(request,template,context)
在客户端,我在javascript中访问jsondata
,如下所示:
var jsondata="{{jsondata}}".replace(/"/g,"\"");
这里jsondata是字符串格式。如果我尝试使用var data = JSON.parse(jsondata);
解析它,则会抛出错误:SyntaxError: JSON.parse: bad control character in string literal at line 1 column 344 of the JSON data
我在jsondata
的344中有空格,但是空格在值的字符串中。
这是我的JSON字符串:
[
{
"model": "posts.feed",
"pk": 1,
"fields": {
"author": "J Watson",
"title": "Service Worker",
"body": "A service worker is a type of web worker. It's essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages.
Because workers run separately from the main thread, service workers are independent of the application they are associated with. This has several consequences:"
}
}]