Ajax Posts但不调用Django View

时间:2013-08-27 01:35:27

标签: javascript jquery python django

问题

发布到我的django视图后,代码似乎只是中途停止。

我有一个Django视图的ajax帖子,它被硬编码以呈现特定的响应(见下文)。当我发布到该视图时,应始终返回该响应,但出于某种原因 视图输出放置所有打印语句,但不放置查询或渲染。我知道我被我的服务器日志重定向(如下所示)。

知道可能导致此行为的原因吗?

服务器日志:

127.0.0.1 - - [26/Aug/2013 21:27:23] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/css/style.css HTTP/1.1" 304 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/js/map.js HTTP/1.1" 200 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/js/home_jquery.js HTTP/1.1" 304 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/js/jquery_cookie/jquery.cookie.js HTTP/1.1" 304 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /favicon.ico HTTP/1.1" 404 -
I've been posted. Here are my values
<QueryDict: {u'name': [u'Mission Chinese Food'], u'address': [u'154 Orchard Street Manhattan']}>
Mission Chinese Food
154 Orchard Street Manhattan
Fish
127.0.0.1 - - [26/Aug/2013 21:27:32] "POST /results/ HTTP/1.1" 200 -

简单的Django视图:

def results(request):
    if request.method == 'POST':
        print "I've been posted. Here are my values"
        print request.POST
        print request.POST.get('name')
        print request.POST.get('address')
    restaurant = Restaurant.objects.filter(name='Fish', address='280 Bleecker St')[0]
    print restaurant
    return render(request, "stamped/restaurant.html", {'restaurant': restaurant}

简单的ajax帖子:

var send_data = { 'name': place.name, 'address': address};

    var csrftoken = $.cookie('csrftoken'); 

    alert(csrftoken);
    alert(send_data);

    function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    } 

    $.ajaxSetup({
        crossDomain: false, // obviates need for sameOrigin test
        beforeSend: function(xhr, settings) {
            if (!csrfSafeMethod(settings.type)) {
                xhr.setRequestHeader("X-CSRFToken", csrftoken);
            }
        }
    });

    $.ajax({ url: '/results/',
        type: 'POST',
        data: send_data,
        success: function(response) {
          console.log("everything worked!");
        },
        error: function(obj, status, err) { alert(err); console.log(err); }
      });




  });

1 个答案:

答案 0 :(得分:0)

使用:

解决
$.ajax({ url: '/results/',
    type: 'POST',
    data: send_data,
    success: function(response) {
      console.log("everything worked!");
      $("#results").html(response);
    },
    error: function(obj, status, err) { alert(err); console.log(err); }
  });

我试图使用Django将其重定向到渲染响应,就像它一样。因为我从javascript调用响应是对javascript和典型的django函数的重新定义。

这部分功能

  success: function(response) {
          $("#results").html(response);
        }, 

将响应呈现给我选择的结果div。