来自django模板,url和视图的Ajax请求

时间:2011-12-06 09:23:58

标签: django templates jquery xmlhttprequest

我有以下设置

网址

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]

我认为我的网址配置是对的吗?如何使用相应的网址和视图解决模板中的ajax请求?

2 个答案:

答案 0 :(得分:2)

这与Ajax无关。

您正在申请网址index/match/622/tab/1。但是您的URLconf期待index/622/1 - 没有'匹配'或'标签'。

答案 1 :(得分:1)

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

请考虑使用{%url(...)%}标记

来构建您的网址