Skip to main content
 首页 » 编程设计

python之下拉列表更改后来自模板的 Django AJAX 调用/url

2024年09月07日43shangdawei

我如何正确地让 django 告诉我要将它发送到的 url,这样我就可以避免对其进行硬编码,以及我如何在 JS 中执行它,一旦它被提供(我可以得到除 recipe_pk 之外的所有 url 和然后在 JS 中连接它?)

网址/路由器

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, 
    } 

请您参考如下方法:

更改模板中设置 url 格式的行,如下所示:

var recipe_pk = $(this).val(); 
request_url = "{% url 'recipes:newRecipeAJAX' '999' %}".replace('999', recipe_pk); 

说明:django生成html时,url标签会在服务端进行解析,形成如下javascript:

request_url = "/path/to/recipe/AJAX/999/".replace('999', recipe_pk); 

如果您在浏览器中查看源代码,您会看到这个。

然后,在客户端,当您的 javascript 被执行时,它会将 999 替换为 recipe_pk 的值。

使用您喜欢的任何占位符而不是 999.. 如果您需要替换采用字符串参数的参数,您可以使用更传统的东西,例如 __ARG__。由于在这种情况下您的 url 正则表达式需要一个整数,因此您的占位符必须是一个整数。

这是我想出的最好的方法.. 只需要在模板中添加少量额外代码,而在 python 中则不需要。不幸的是,Django 最初设计时并没有考虑到 AJAX ...如果有一个特殊的反向函数返回包含参数名称作为占位符的 URL 来代替参数值,那就太好了,但据我所知,有没有。