【问题标题】:Unable to process Ajax/jQuery request in Django back end无法在 Django 后端处理 Ajax/jQuery 请求
【发布时间】:2013-11-03 16:31:51
【问题描述】:

下面是我处理 Ajax/jQuery 请求的 Django 代码。带有“q”参数的 Django 过滤器方法不起作用。这可能是因为 Ajax 请求是 JSON 格式。有人可以建议我哪里出错了吗?

Views.py

def get_names(request):
   q = request.GET.get('term', '')
   names = Names.objects.filter(names__startswith=q)[:10]
   results = []
   if names.count > 0:
      for name in names:
        name_json = {}
        name_json['id'] = name.id
        name_json['label'] = name.name
        name_json['value'] = name.name
        results.append(name_json)
        data = json.dumps(results)
   else:
         data = 'fail'

   mimetype = 'application/json'
   return HttpResponse(data, mimetype)

下面是我的 jQuery 代码

$( document ).on( "pageinit", "#myPage", function() {
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
    var $ul = $( this ),
        $input = $( data.input ),
        value = $input.val(),
        html = "";
    $ul.html( "" );
    if ( value && value.length > 2 ) {
        $ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
        $ul.listview( "refresh" );
        $.ajax({
            url: "/get_names/",
            dataType: "json",
            crossDomain: true,
            data: {
                term: $input.val()
            }
        })
        .then( function ( response ) {
            $.each( response, function ( i, val ) {
                html += "<li>" + val + "</li>";
            });
            $ul.html( html );
            $ul.listview( "refresh" );
            $ul.trigger( "updatelayout");
        });
    }
});});

【问题讨论】:

  • 为什么是crossDomain: true,

标签: jquery ajax django django-views


【解决方案1】:

根据jquery docs,dataType 影响响应,而不是请求,所以这不应该是你的问题。尝试在视图开头添加print request.GET - 这应该告诉您是否实际发送了 term 参数。我唯一的另一个想法是你的 $input 在某个时候失去了它的价值——可能是由$ul.listview( "refresh" );触发的? - 你应该改变

data: {
    term: $input.val()
}

data: {
    term: value
}

因为您已经进一步检索了该值。

【讨论】:

  • 感谢您的回复。当我尝试打印 request.GET 时,我得到&lt;QueryDict: {u'q': [u'john']}&gt;。我试图在我的 django 方法中将这种情况下的查询“john”分配给“q”,以便相应地过滤我的数据库。此外,将术语从 $input.val() 更改为 value 也无济于事。
  • 奇怪的是你发送了一个term变量,但是一个q变量到达了服务器。所以你的 django 变量 q 将是空字符串。
猜你喜欢
  • 1970-01-01
  • 2013-06-13
  • 2023-03-06
  • 2020-10-25
  • 2016-12-23
  • 2014-04-28
  • 1970-01-01
  • 1970-01-01
  • 2023-01-14
相关资源
最近更新 更多