【问题标题】:Ajax get returns empty dataAjax get 返回空数据
【发布时间】:2010-12-03 17:23:02
【问题描述】:

当数据变量应该返回“OK”或“EXISTS”时,它什么也不返回。

我有一个带有叠加效果的模板。 income.html 模板有一个表单和一个“添加新类别”按钮,当您单击它时,会显示一个带有小表单的新窗口(叠加效果)。

收入.html:

(document).ready(function(){ 
$("#new_cat").live("click", ( function() {      
    var cat_name = $("#nc").val();
    if (cat_name) {
        $.get("/cashflow/new_cat/0/", { name: cat_name, account: {{ account }} },
          function(data){
            if (data == "OK") {
                $("#id_category").val(cat_name);
            }
            if (data == "EXISTS") {
                var error = "The category already exists";
                alert(error);
            }
          });
    }
    else {
         var error = "Please enter a name";
         alert(error);
    }
}))  
});
</script>
...

<form>{% csrf_token %}
       <label for="name">Name:</label><input type="text" id="nc" />
       <input type="submit" value="Submit" id="new_cat" />
</form>

views.py:

@login_required
def income(request, account_name): 
    account = account_name
    if request.method == 'POST':
        form = TransForm(user=request.user, data=request.POST)
        if form.is_valid():
            income = form.save(commit=False)
            income.type = 0
            income.account = Account.objects.get(
                            name = account_name,
                            user = request.user)
            income.name = form.cleaned_data['name']
            income.category = form.cleaned_data['category']
            income.save()
            uri = ("/cashflow/account/%s") % str(account_name)
            return HttpResponseRedirect(uri)

    else:
        form = TransForm(user=request.user)

    context = {
          'TransForm': form,
          'type': '0',
          'account': account, 
    }
    return render_to_response(
        'cashflow/income.html',
        context,
        context_instance = RequestContext(request),
    )

def new_cat(request, type):
    if request.method == u'GET':
        GET = request.GET
        if GET.has_key(u'name'):
            name = request.GET[u'name']
            account = request.GET[u'account']
            c = Category.objects.filter(name=name, account=account)
            if c:
                s = "EXISTS"
            else:
                c = Category(name = name, user = request.user, 
                        type = type, account = account)
                c.save()
                s = "OK"

    return HttpResponse(s)

【问题讨论】:

  • 所有浏览器的一致问题?
  • 你能调试你的服务器端代码吗?正在执行吗?
  • 是的,所有的 django 代码都在执行中。

标签: ajax django


【解决方案1】:

您是否跨域?您不能进行跨域 ajax 请求。这包括子域。

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 2015-08-02
    • 2013-12-04
    • 1970-01-01
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多