作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 Django 上创建了不同的基于类的 View 。在 HTML 上,我创建了一些表单,使用 AJAX 发出请求。我的问题是它给了我
不允许的方法 (POST)
我不知道我做得是否正确,或者是否需要修改某些内容才能使其正常工作。
我的view.py是这样的
class Landing(View):
def get(self,request):
if request.method == 'POST':
if request.is_ajax():
data = {"lat":20.586, "lon":-89.530}
print request.POST.get('value')
return JsonResponse(data)
return render(request,'landing.html',{'foo':'bar'})
我从 Javascript 发送请求
$(document).ready(function() {
$('#productos').on('change', function(e) {
//Call the POST
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var value = $('#productos').val();
$.ajax({
url: window.location.href,
type: "POST",
data: {
csrfmiddlewaretoken : csrftoken,
value : value
},
success : function(json) {
console.log(json);
drop(json);
},
error : function(xhr,errmsg,err){
console.log(xhr.status+": "+xhr.responseText)
}
});
});
});
我从网上得到了一些代码,但我真的不知道如何使用它,因为他们在没有基于类的 View 的情况下使用它。
那么,我的代码需要什么来接受 POST 方法?
最佳答案
基于类的 View 的 dispatch
方法决定调用哪个函数,到目前为止,您已经编写了 get
函数,但没有 post
> 函数,因此只需将逻辑移至后置函数中即可。
class Landing(View):
def post(self,request):
if request.is_ajax():
data = {"lat":20.586, "lon":-89.530}
print request.POST.get('value')
return JsonResponse(data)
def get(self, request):
return render(request,'landing.html',{'foo':'bar'})
关于javascript - 如何在 Django 中向基于类的 View 发出 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42447679/
我是一名优秀的程序员,十分优秀!