【问题标题】:How to change the type in the ajax如何更改ajax中的类型
【发布时间】:2013-02-19 08:17:06
【问题描述】:
template.html
<script >
$(document).ready(function() {          


var a="{{parameter}}";

    $.ajax({
    type :'GET',

    url : geturl(a),

    dataType : 'json',


views.py
if param=="daywise":

    print request.method
    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

我实际上是通过发送表单数据来执行 post 方法的。但它有一个获取请求,因为我已经在 ajax 脚本中给出了 GET 类型。我正在查看视图。如果 request.method=="POST" 但此方法仍然是 GET

【问题讨论】:

  • 有什么问题?也许将type :'GET', 更改为type :'POST',

标签: django


【解决方案1】:

将类型更改为 POST...

var a="{{parameter}}";

    $.ajax({
    type :'POST',

    url : geturl(a),

    dataType : 'json',

如果你没有在 django 中禁用 CSRF 中间件,会导致问题。 要修复它,请在 &lt;script&gt; 标记之后和 $(document).read... 之前添加此脚本:

$.ajaxSetup({ 
        beforeSend: function(xhr, settings) {
            function getCookie(name) {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                     // Does this cookie string begin with the name we want?
                     if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                     }
                 }
             }
             return cookieValue;
         }
         if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
             // Only send the token to relative URLs i.e. locally.
             xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
         }
     } 
 });

【讨论】:

  • 我想要一个 GET 以及一个 POST 请求。 GET 加载 sumthin 默认值,然后 POST 是当我想根据我通过表单发送的 wat 数据检索数据时
  • 您需要分开通话
猜你喜欢
  • 1970-01-01
  • 2012-10-16
  • 2021-05-16
  • 2012-08-27
  • 2011-03-05
  • 2013-11-02
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多