将动态javascript变量作为url传递到模板中

问题描述 投票:0回答:1

我正在尝试在JavaScript中创建动态网址以传递给我的html模板。

在我的js中,我有:

// dynamic url to edit flashcard
function createDynamicURL()
{
    //The variable to be returned
    var URL;

    //The variables containing the respective IDs
    var cardID= cards.cards[current_card].id   //this is defined earlier

    //Forming the variable to return
    URL-="study/[1-9][0-9]/";
    URL+="card-edit/";
    URL+=cardID;

    return URL;
}

并且在我的模板中,我有:

<a id="edit-button" class="btn btn-default btn-warning" href="javascript:window.location=createDynamicURL();"  >Edit</a>

我的urls.py:

app_name = 'flash'

urlpatterns = [
    re_path(r'^study/(?P<deck_id>[0-9]+)/$', views.study, name='study'),
    re_path(r'^study/(?P<deck_id>[0-9]+)/get_cards/$', views.get_cards, name='get-cards'),
    path("decks/",views.DeckList.as_view(),name="deck-list"),
    path("decks/<int:pk>/",views.DeckDetail.as_view(),name="deck-detail"),
    path("cards/<int:pk>/", views.CardList.as_view(), name="flash-list"),
    path("card-edit/<int:pk>/",views.CardEdit.as_view(),name="flash-edit"),
    path("card-detail/<int:pk>/",views.CardDetail.as_view(),name="flash-detail"),
    path("edit/<int:pk>/",views.DeckUpdate.as_view(),name="edit"),
    path("",views.home,name="home"),

]

单击时获得的网址:http://127.0.0.1:8000/%2Fflash/study/33/NaNcard-edit/51

正确的网址应该是:http://127.0.0.1:8000/%2Fflash/card-edit/51/

所以至少它给了我正确的ID。但是为什么它会给我NaN,又如何摆脱研究/ 33?请注意,33并不总是33,在这里我无法访问该ID,因此我希望它只能是任何2位数字。

我对javascript没有太多的经验,所以很抱歉这个基本问题。任何建议将不胜感激!

研究视图:

@login_required
@ensure_csrf_cookie
def study(request, deck_id):
    """
    Study cards page (JS driven)
    """
    if request.method == 'GET':
        return render(request, 'flash/study.html')


@login_required
@csrf_exempt
def get_cards(request, deck_id):
    """
    Get cards to study (ajax)
    """

    if request.method == 'GET':
        cards = Flashcard.objects.filter(owner=request.user, deck=deck_id,
                                         next_due_date__lte=timezone.now())
        count = len(cards)
        data = {'count': count, 'cards': []}

        num = count if count < CARD_LIMIT else CARD_LIMIT
        if num:
            # generate list of random indexes
            idx = random.sample(range(count), num)
            for i in idx:
                card = cards[i]
                question = '<p>'+'</p><p>'.join(card.question.split('\r\n'))+'</p>'
                answer = '<p>'+'</p><p>'.join(card.answer.split('\r\n'))+'</p>'
                data['cards'].append({'id': card.pk, 'question': question,
                                     'answer': answer})

        return JsonResponse(data)
    else:
        data = json.loads(str(request.body, 'utf-8'))
        for res in data:
            card = Flashcard.objects.get(owner=request.user, pk=res['id'])
            card.save(rating=res['result'])

        return JsonResponse({'status': 'OK'})
javascript django function url dynamic-url
1个回答
0
投票

如果模板中有卡片对象,请尝试以下步骤:

<a id="edit-button" class="btn btn-default btn-warning" href="{% url 'flash-edit' card.id %}"  >Edit</a>
© www.soinside.com 2019 - 2024. All rights reserved.