【问题标题】:Ajax request from django template, url and view来自 django 模板、url 和视图的 Ajax 请求
【发布时间】:2012-01-13 22:04:55
【问题描述】:

我有以下设置

网址

urlpatterns = patterns('',
   (r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.STATIC_DOC_ROOT}),
    url(r'^index/$','pMass.views.index', name='index'),
    url(r'^index/(?P<match>\d+)/(?P<tab>\d)$', 'pMass.views.detail',name='detail'),

查看

def index(request):
    error = False
    cid = request.GET

    if 'cnum' in request.GET:
       cid = request.GET['cnum']

    if not cid:
       error = False
       expcount = Experiment.objects.count()
       allmass = SelectedIon.objects.count()

    else:

        defmass = 0.000001
        massvalue = float(cid)
        masscon = defmass * massvalue
        highrange = massvalue + masscon
        lowrange = massvalue - masscon

        myquery = SelectedIon.objects.select_related().filter(monoiso__range=(lowrange, highrange))
        querycount = myquery.count()

        return render_to_response('queryresult1.html', {'query': cid, 'high':highrange, 'low':lowrange, 'sections':myquery, 'qcount':querycount, })


    return render_to_response('index.html', {'error': error, 'exp': expcount,'mass':allmass,})


def detail(request,  match, tab):
    monorecord = get_object_or_404(SelectedIon, monoiso=match)
    detailrec = SelectedIon.objects.filter(monoiso=monorecord)
    return render_to_response('queryresult1.html', {"id": monorecord, "detail": detailrec}, context_instance=RequestContext(request))

模板 // from where I am trying to send request

$("td a").bind("click", function(event){

        var str = $(this).attr('id');
        tab = $("ul.tabs li").find("a").attr('id');
        mapurl = 'match/'+ str+ '/tab/'+ tab;

        new $.ajax({
        url: mapurl,
        async: true,
        // The function below will be reached when the request has completed
        success: function(transport)
        {
            $("#result").html(transport); // Put data in the div
            $("result").fadeIn();        // Fade in the active content
        }
    });

我正在尝试将 ajax 请求 发送到服务器并在同一个 queryresult1.html 模板(结果容器)中获取结果。但是,我的请求遇到了问题

`Error`     [11:18:37.814] GET http://127.0.0.1:8000/index/match/622/tab/1 [HTTP/1.0 404 NOT FOUND 59ms]

我认为我的 url 配置是正确的?如何解决我的 ajax 来自模板的请求 与它的相应 url 和视图?

【问题讨论】:

    标签: django templates jquery xmlhttprequest


    【解决方案1】:

    这与 Ajax 无关。

    您正在请求 URL index/match/622/tab/1。但是您的 URLconf 需要 index/622/1 - 没有“匹配”或“制表符”。

    【讨论】:

    • 我修复了 url,但开始得到 [11:43:47.154] GET 127.0.0.1:8000/index/622/1 [HTTP/1.0 500 INTERNAL SERVER ERROR 164ms]
    • 所以,您的视图代码中存在错误。查看 Firebug 以查看详细的回溯。
    【解决方案2】:

    我不确定,但我认为您应该尝试: http://127.0.0.1:8000/index/622/1 匹配给定的 url 模式。

    考虑使用 {% url (...) %} 标签构建您的网址

    【讨论】:

      猜你喜欢
      • 2012-01-08
      • 1970-01-01
      • 2020-08-31
      • 2019-03-14
      • 1970-01-01
      • 2015-10-14
      • 2011-11-17
      • 1970-01-01
      • 2020-08-21
      相关资源
      最近更新 更多