[英]Django Ajax Post with HTML content using JSON.stringify then json.loads error
我在具有“HTML”內容的網頁上的表單中有一個文本區域。
<!-- HTML -->
<textarea id="my-textarea">
<div class="this">Content here & here!</div>
</textarea>
我使用 Javascript 獲取內容並使用 encodeURIComponent 為 AJAX JSON 安全地編碼字符串。 並將其存儲到鍵/值數組中。 (蟒蛇字典)
// Javascript
var textarea = document.getElementById('my-textarea').value;
var data = {};
data['html'] = encodeURIComponent(textarea);
console.log(data);
// prints --> {html: "%3Cdiv%20class%3D%22this%22%3EContent%20here%20%26amp%3B%20here%3C%2Fdiv%3E"}
// In AJAX function.
var json = "data=" + JSON.stringify(data);
然后我將數據發送到基於 Django 類的視圖,然后我有
# Python / Django
if request.is_ajax():
print(request.POST)
# prints --> <QueryDict: {'data': ['{"code":"<div class="this">Content here & here</div>"}']}>
data = request.POST.get('data', None)
if data:
data = json.loads(data)
這會引發如下錯誤:
Traceback (most recent call last):
File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 71, in view
return self.dispatch(request, *args, **kwargs)
File "/home/tr/dev/host-root/apps/trenddjango2/django/common/views/dashboard/mixins.py", line 56, in dispatch
return super(TemplateDashboardMixin, self).dispatch(request, *args, **kwargs)
File "/home/tr/dev/host-root/apps/trenddjango2/venv/lib/python3.8/site-packages/django/views/generic/base.py", line 97, in dispatch
return handler(request, *args, **kwargs)
File "/home/tr/dev/host-root/apps/trenddjango2/django/common/views/dashboard/catalogue.py", line 550, in post
data = json.loads(jsonData)
File "/usr/local/lib/python3.8/json/__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python3.8/json/decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python3.8/json/decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 22 (char 21)
我發現如果刪除 class="this" 中的"" 雙引號,字符串將正確加載。
我的問題是:如何在 python 中加載帶有雙引號的 JSON 字符串,即使它被轉義為 %22 ?
使用\\\\
來逃避它。
json.loads('{"code":"<div class=\\"this\\">Content here & here</div>"}')
這將按您的預期工作。 下面的例子向你展示了如何逃脫。
'<div class="this">Content here & here!</div>'.replace(/"/g, '\\\\"')
結果是:
"<div class=\\"this\\">Content here & here!</div>"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.