我有一个简单的API,我从请求中获取JSON数据并解析它。上面的API工作正常POSTMAN但不适用于jquery。
在views.py中:
def search_and_return(request):
print(request.body.decode() , type(request))
request = request.body.decode()
request = json.loads(request)
client_id=int(request["order_clientId"])
start_date=request["order_start_dt"]
end_date=request["order_end_dt"]
print(client_id, start_date, end_date)
form.html:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="form.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js"></script>
<script type="text/javascript" src="form.js"></script>
</head>
<body>
<p>Client ID</p><input type="text" name="client_id" id="clientid"><br>
<p>Sub Client ID</p><input type="text" name="sub_client_id" placeholder="optional" id="subclientid"><br>
<p>Start Date(And Time)</p><input type="datetime-local" name="start_date" id="startdate"><br>
<p>End Date(And Time)</p><input type="datetime-local" name="end_date" id="enddate"><br>
<input id="button" type="submit" name="Submit">
</body>
</html>
在我的javascript中:
$(document).ready(function() {
$("#button").click(function() {
$.ajax({
url:"http://10.124.92.208:8000/customer/retrieve_info",
crossDomain:true,
data: {"order_clientId" : 114, "order_start_dt" : "2016-01-01T21:25:22", "order_end_dt" : "2016-01-05T21:25:22"},
type:"POST",
dataType:"json",
})
.done(function(json){
alert(json);
});
});
});
当我从POSTMAN发送请求时,我按预期得到以下输出:
{"order_clientId" : 114, "order_start_dt" : "2016-01-01T21:25:22", "order_end_dt" : "2016-01-05T21:25:22"} <class 'django.core.handlers.wsgi.WSGIRequest'>
114 2016-01-01T21:25:22 2016-01-05T21:25:22
当我从自定义html或JS发送请求时,我得到以下输出和错误:
order_clientId=114&order_start_dt=2016-01-01T21%3A25%3A22&order_end_dt=2016-01-05T21%3A25%3A22 <class 'django.core.handlers.wsgi.WSGIRequest'>
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
我希望收到的JSON数据与从POSTMAN收到的数据完全相同。我应该做些什么改变?我认为这是Javascript中的一个问题,因为POSTMAN工作得很好。在django-views中从POST请求获取数据的最佳方法是什么?
答案 0 :(得分:1)
解析数据时需要使用JSON.stringify(arr)
$(document).ready(function() {
$("#button").click(function() {
$.ajax({
url:"http://10.124.92.208:8000/customer/retrieve_info",
crossDomain:true,
data: JSON.stringify({"order_clientId" : 114, "order_start_dt" : "2016-01-01T21:25:22", "order_end_dt" : "2016-01-05T21:25:22"}),
contentType: 'application/json; charset=utf-8',
type:"POST",
dataType:"json",
})
.done(function(json){
alert(json);
});
});
});