【发布时间】:2018-03-09 11:49:16
【问题描述】:
我如何正确地让 django 告诉我要将其发送到的 url,这样我就可以避免对其进行硬编码,以及如何在 JS 中执行它,一旦它被提供(我可以得到除了 @987654321 之外的所有内容的 url @ 之后再在 JS 中 concat ?)
网址/路由器
url(r'^recipe/AJAX/(?P<recipe_pk>[a-zA-Z0-9]+)/?', views.newRecipeAJAX, name='newRecipeAJAX'),
在模板中
{% block script_inline %}
$(function(){
$('#form-dropdown').change(function () {
var recipe_pk = $(this).val();
{# This one doesn't know the recipe_pk yet, so it throws a NoReverseMatch error #}
request_url = {% url 'recipes:newRecipeAJAX' recipe_pk=recipe_pk %};
{# This one will too, since it doesn't have the argument #}
request_url = {% url 'recipes:newRecipeAJAX' %};
{# Tried to get a valid link, then JS remove it and add the correct pk, but it throws a JS console error of 'Uncaught SyntaxError: Invalid regular expression flags'#}
request_url = "'' + {% url 'recipes:newRecipeAJAX' recipe_pk=1 %} + "'";
alert(requst_url)
// AJAX Land
});
});
{% endblock script_inline %}
查看
def newRecipeAJAX(request, recipe_pk):
if request.method == 'POST':
return HttpResponseRedirect('/dashboard')
# GET
else:
recipe_requested = get_object_or_404(Recipe, pk=recipe_pk)
related_recipes = Recipe.related_recipes.all()
return {
'recipe_requested': recipe_requested,
'related_recipes': related_recipes,
}
【问题讨论】:
-
您的网址以
?结尾。你检查了吗?