【问题标题】:Why does my Django request.method does not match POST为什么我的 Django request.method 与 POST 不匹配
【发布时间】:2013-02-03 23:00:09
【问题描述】:
$.ajax({
    type :'GET',

    url : geturl(a),
    // type: $(this).attr('method'),
    dataType : 'json',

views.py:

  if request.method=="POST":


        if request.POST.get('monyrsubmit'):

            monthform=MonthForm(request.POST)
            if monthform.is_valid():
                selected_month=monthform.cleaned_data["Month"]
                selected_year=monthform.cleaned_data["Year"]
                print selected_month
                print selected_year  

我可以在 ajax 的类型字段中同时包含 GET 和 POST 请求吗?我使用表单并且仅当单击提交按钮时我试图根据提交的数据显示信息。如果 request.POST.get('monyrsubmit') 不起作用。 帮助将不胜感激

【问题讨论】:

  • 想必您已经在 AJAX 部分中使用 type: 'POST' 尝试过?您在 Firebug 或 Chrome Inspector 网络面板中看到了什么?我最好的猜测是你正在攻击 Django 的 CSRF 保护。

标签: django


【解决方案1】:

这很简单。您必须抽象事件。

function event_page_load() {
   function ajax_request('GET')
}

function click_submit_button() {
   function ajax_request('POST')
}

function ajax_request(type) {

 $.ajax({
    type : type,
    ......
    ......
 })
}

您还可以考虑以下一般准则。 GET 和 POST 应该根据对服务器的请求类型来使用

 - If you are reading the existing data(without modification) from the server, use GET
 - if you are writing/modifying any data in the server, use POST

在jQuery中,你可以使用这些简单的方法。

对于 GET 请求

$.get(  
    url,  
    {param1: "value1", param2: "value2"},  
    function(responseText){  
        // todo ;  
    },  
    "html"  
);  

对于 POST 请求

$.post(  
    url,  
    {param1: "value1", param2: "value2"},  
    function(responseText){  
        // todo ;  
    },  
    "html"  
);  

确保您已禁用浏览器缓存。

$.ajaxSetup ({  
        cache: false  
    });

在django端,可以使用request.is_ajax()方法来验证ajax调用,可以根据request.method属性进行过滤。

您可以在https://github.com/sivaa/django-jquery-ajax-exmapleshttps://github.com/sivaa/django-jquery-ajax-exmaples 上参考 AJAX 与 Djano 的所有可能用法

【讨论】:

    猜你喜欢
    • 2018-10-11
    • 2021-08-15
    • 1970-01-01
    • 2018-01-30
    • 2021-01-29
    • 2017-11-27
    • 2021-09-30
    • 2014-12-07
    • 1970-01-01
    相关资源
    最近更新 更多