【问题标题】:jquery post request + response in DjangoDjango中的jquery发布请求+响应
【发布时间】:2014-10-18 00:39:58
【问题描述】:

我正在尝试在 Django 中使用 jquery 进行发布请求。不幸的是,我还没有成功。确实:我只在萤火虫中看到状态为 200 的发布请求,我得到以下结果(太新,无法发布任何图像):

https://drive.google.com/a/essec.edu/file/d/0B5MagNFQFkbXeVBNV1pfZC1sbk0/view?usp=sharing

谁能帮我找出我做错了什么?

我的代码来自这里: Need a simple working ajax example for django forms ,所以我认为应该是正确的。

仅供参考,在 settings.py 中,我已经评论了 csrf 行以暂时解决该问题:

" #'django.middleware.csrf.CsrfViewMiddleware',"

views.py:

import json
from django.shortcuts import render
from django.http import HttpResponse


def index(request):

    return render(request, 'index.html')


def ajax_test(request):
    if request.method == 'POST' and request.is_ajax():
        name = request.POST['name']
        city = request.POST['city']
        message = name + ' lives in ' + city

        return HttpResponse(json.dumps({'message': message})) 

    return render(request, 'ajax.html')

index.html:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/static/js/ajax.js"></script>
<script src="http://getbootstrap.com/dist/js/bootstrap.js"></script>


<form id="my_form" action="" method="post">
<input type="submit" value="Send">
</form>

ajax.js:

$(document).ready(function(){

  $("#my_form").submit(function(){
    $.post("",
    {name:"Donald Duck",
     city:"Duckburg",
     },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    })
    .fail(function(xhr) {
        console.log("Error: " + xhr.statusText);
        alert("Error: " + xhr.statusText);
    });
    return false;
  });

});

urls.py:

from django.conf.urls import patterns, url

from polls import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^ajax/$', views.ajax_test, name="ajax"),
)

【问题讨论】:

    标签: jquery ajax django


    【解决方案1】:

    我敢打赌你的表单动作。尝试将其设置为您的帖子的 URL。

    【讨论】:

      【解决方案2】:

      您的表单没有定义“动作”

      $.post("",
      

      这必须定义 url。改成

      $.post("/ajax/",
      

      此外,当您正确实施它时,不要摆脱 csrf 令牌。您可以简单地传递序列化的表单数据(其中将包括 csrf 令牌)。

      【讨论】:

        猜你喜欢
        • 2012-09-26
        • 2015-03-10
        • 1970-01-01
        • 2016-08-21
        • 1970-01-01
        • 2017-07-29
        • 2019-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多