javascript - 未调用 AJAX 回调

标签 javascript jquery ajax django

这是我的 ajax 函数:

function ajax_call(call_method,data_to_send) {
    logger("function ajax_call. var data_to_send: ");
    logger(data_to_send);
    $('.clickable save_button').hide()
    $.ajax({
      type: 'POST',
      url: call_method,
      data: data_to_send,
      success: function(data){
            logger("data returned to page after ajax call: ");
            logger(data);
            $('.error_msg').html("Successfully saved record to database.");
            $('.error_msg').fadeIn('slow');
            setTimeout("$('.error_msg').fadeOut('slow');",5000); // 5 secs to give user enough time to read
            $('.clickable save_button').show()
            response_dispatcher(data); // This should contain object type at least
      },
      failure: function(){
            $('.error_msg').html("There was an error while saving this information. Please try again. " +
                                    "If the error persists, please contact us using the contact form.");
            $('.error_msg').show;
            $('.clickable save_button').show()
      },
      dataType: 'json'
    });
}

而且,这是在后端发送到我的方法的数据: { '显示顺序':“3”, '目标':“虚拟目标”, 'id':-1, 'object_type':“目标”

我已在我的应用程序中验证收到了相同的数据。

这是我的 Django View 方法:

@login_required
def update_goal_view(request):

    if request.method == 'POST' and request.is_ajax:
        # Example data sent from AJAX Request
        #qd = {u'display_order': [u'23'], u'object_type': [u'goal'], u'goal': [u'dummy goal'], u'id': [u'-1']}
        qd = request.POST
        goal = qd.get('goal','')
        display_order = qd.get('display_order',99999)
        id = int(qd.get('id',''))
        object_type = qd.get('object_type','')

    # For now, just return something to test populating data to the page
    id = '100'
    goal = 'goal returned'
    object_type = object_type
    data = {'id':id,'goal':goal,'object_type':object_type}
    return HttpResponse(data,mimetype="application/json")

在 Firebug 中,我在 ajax 调用后看到了这个:

POST http://127.0.0.1/xml/update_goal 200 OK 12ms

问题是,当我的成功回调似乎从未被调用时...我这么说是因为正如您从上面看到的那样,我应该有一条消息写入我的记录器,但没有。我知道我的记录器可以正常工作,因为回调之外的所有其他消息都会写入我的记录器。

最佳答案

我认为 Django 不会对字典进行自动序列化。您必须手动将它们序列化为 JSON。

import simplejson

# ...

return HttpResponse(simplejson.dumps(data), mimetype="application/json")

关于javascript - 未调用 AJAX 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3397403/

相关文章:

javascript - 带有句法着色的 Json Pretty Print

php - 如何使用 laravel 查询生成器 'when' 运算符定位同一结果集的列

javascript - 限制函数中动态列表项的数量

javascript - 无法将字符串传递给 onClick 函数 :Ruby on Rails

javascript - 在索引达到特定数字后,如何在每个循环中重置索引

javascript - 禁用 Google 地球插件的用户交互

javascript - ReactClassInterface : You are attempting to define `constructor` on your component more than once. 此冲突可能是由于 mixin

javascript - 附加到 div 变慢

jQuery .autocomplete() 在一个输入字段中包含邮政编码和城市名称

javascript - 将事件绑定(bind)到 AJAX 的子元素