gpt4 book ai didi

javascript - 使用 Django View 的 Ajax 请求 - 错误地捕获变量

转载 作者:行者123 更新时间:2023-12-02 18:43:06 25 4
gpt4 key购买 nike

我已经使用其他代码示例成功地将数据从我的网址传递到我的 View ,所以我不确定为什么这个有什么不同,但这是我对 View 的 ajax 调用的内容。我正在尝试传递 id 和可选的深度参数:

链接/urls.py
urlpatterns += patterns('links.ajax',
url(r'^ajax/(?P<id>\d+)*$', 'ajax_graph_request', name='ajax_graph_request'),
)

链接/ajax.py
import json
from django.http import HttpResponse, HttpResponseRedirect

def ajax_graph_request(request, id):
depth = request.GET.get('depth','1')
result = {'id':id, 'depth':depth}
data = json.dumps(result)
return HttpResponse(data, mimetype='application/json')

请求

console.log(record);
$.getJSON("/ajax/", { id:record, depth:2 }).done(function( data ){
console.log(data);
});

响应

22145 (from js console print)
{"depth": "2", "id": null}

因此请求被正确地传播到正确的 View ,但变量却没有。这是为什么?

最佳答案

您的网址模式是 ajax/(?P<id>\d+)即 View ajax_graph_request预计 id作为参数。通过将其作为数据参数发送 { id:record, depth:2 } 。它作为 kwarg 传递而不是参数id

更改 .getJson方法

$.getJSON("/ajax/"+record, { depth:2 }).done(function( data )

它会工作得很好。

关于javascript - 使用 Django View 的 Ajax 请求 - 错误地捕获变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16681699/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com