Javascript 如何修复多值错误
我正在尝试使用Javascript获取Django项目中每个页面花费的时间。我不断地得到一个错误,所以我正在尝试修复它 错误:Javascript 如何修复多值错误,javascript,python,django,Javascript,Python,Django,我正在尝试使用Javascript获取Django项目中每个页面花费的时间。我不断地得到一个错误,所以我正在尝试修复它 错误: MultiValueDictKeyError at /backendurl/ 'timeSpent' views.py中突出显示的错误行: timeSpent = request.POST['timeSpent'] def my_view_function(request): timeSpent = request.POST['timeSpent']
MultiValueDictKeyError at /backendurl/
'timeSpent'
views.py中突出显示的错误行:
timeSpent = request.POST['timeSpent']
def my_view_function(request):
timeSpent = request.POST['timeSpent']
response = json.dumps({
'timeSpent' : timeSpent,
})
return HttpResponse(response)
以下是模板中的javascript:
<script>
$(document).ready(function() {
var startDate = new Date();
$(window).unload(function() {
var endDate = new Date();
$.ajax({
type: POST,
url: "backendurl", // be mindful of url names
data: {
'timeSpent': endDate - startDate || 'none' // defaults to a string
},
success: function(response) {
// unpack response:
status = response.status
}
})
</script>
这是url.py
path('backendurl/', views.my_view_function, name='backendurl'),
在大多数情况下,键
'timeSpent'
不存在于请求中。POST
要从请求中获取键的值。POST
dict需要使用多值dict的get方法
您还可以设置一个默认值,以知道您的请求中没有密钥,在下面的示例中为-1
timeSpent = request.POST.get('timeSpent', -1)
idk js端,但是,问题是,在您的POST负载中,名为
timespunt
的密钥不存在,您正在尝试访问Django中的同一密钥。现在有了进展,它没有显示错误,但只显示{“timespunt”:-1}
是的,这只是为了避免错误,它是-1,因为您没有从request.POST
获得'timeSpent'
。