我正在将JSON数据发送到django程序。我在解码数据时遇到问题。
在javascript中,我将封装两个数组的对象转换为JSON,然后将其读回。
Javascript:
data = {
"RegAvStart": reg_start,
"RegAvStop": reg_end
};
data = $(this).serialize() + "&" + $.param(data);
console.log(data);
var jsondata = JSON.stringify(data);
console.log("JSON:" + jsondata);
在这里,reg_start和reg_end都是字符串数组。 在控制台中,我得到:
JSON:"&RegAvStart%5B%5D=05%3A00%20AM&RegAvStart%5B%5D=05%3A30%20PM&RegAvStop%5B%5D=08%3A00%20AM&RegAvStop%5B%5D=09%3A30%20PM"
我的django(python)代码:
def save_doctorslots(request, cliniclabel, doctor_id):
doctor_id=int(doctor_id)
doc = get_object_or_404(doctor, docid=doctor_id)
cl = Clinic.objects.get(label=cliniclabel)
print("Clinic name", cl.name)
if request.method == 'POST':
msg ="Received SaveSlots data for doctor %d clinic %s" % (doctor_id, cliniclabel)
print(msg)
print(request.POST)
regavst = request.POST.get('RegAvStart[]')
print(type(regavst))
if not regavst is None:
regular_available_start = json.loads(regavst)
else:
print("Didnt get regular available hours")
输出:
Received SaveSlots data for doctor 1 clinic joelent
<QueryDict: {'RegAvStart[]': ['05:00 AM', '05:30 PM'], 'RegAvStop[]': ['08:00 AM', '09:30 PM']}>
<class 'str'>
2018-10-04 10:45:53,000 django.request ERROR Internal Server Error: /clinic/joelent/doctor/save/slots/1
Traceback (most recent call last):
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
response = get_response(request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/joel/.local/lib/python3.6/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view
return view_func(request, *args, **kwargs)
File "/home/joel/myappointments/clinic/views.py", line 261, in save_doctorslots
regular_available_start = json.loads(regavst)
File "/usr/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/usr/lib/python3.6/json/decoder.py", line 342, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 2 (char 1)
答案 0 :(得分:1)
这里完全不需要JSON。您已经序列化了数据,因此它是格式编码的格式;进行JSON.stringify
只会增加另一个毫无意义的序列化级别。删除该行,然后直接在您的Ajax函数中发送data
。