无法使用ajax django显示信息

时间:2015-12-22 18:20:57

标签: jquery ajax django

我正在尝试使用ajax显示大小但是在ajax成功后它没有出现

这是ajax脚本

<script type="text/javascript">
    function getStoreView(event, productId) {
        event.preventDefault();   
        var data = {
           productId : productId
        }
        // Send productId as query param of url
        $.ajax({        
            type: "GET",
            url: "{% url 'storeView'  user=store.user %}",
            data: data,
            success: function(data) {
              var html = "";
              $.each(data.sizes, function(index,sizes) { 
              console.log(sizes.value) 
            });
            },

            error: function(response, error) {
                alert(error);  
            }
        });
    };
</script>

这是模板

    <form id="form" action="{% url 'storeView'  user=store.user %}" method="post"  />
                      {% csrf_token %}          

                      <div class="increment">
                      {% for size in sizes %}

                      <strong class="pull-left">{{size}}:</strong> 
                      <input type = "number" name="quantity" value="{{product.quantity}}">
                      <input type = "hidden" name = "size" value="{{size}}">
                      <input type = "hidden" name = "productid" value = "                              {{product.id}}">
                       {% endfor %}
                      </div>
                      <input type="submit" value="submit" id="submit"/>
                     </form>

这里是views.py

if request.user.is_authenticated():
        productid = request.GET.get('productId')
        if request.is_ajax():
            try:
                sizes = StoreProduct.objects.get_size(productid)
            except:
                sizes = None

            sizes = list(sizes.values())

            data = {
            "sizes" : sizes
            }

            return JsonResponse(data)

我可以控制记录大小,但我如何在forloop中显示它们?

根据Hybrid的回答,生成以下追溯

File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\lenovo\Desktop\plump\Plumpin\src\store\views.py" in StoreView
  61.           return render(request , "store/storeform.html" , {'sizes' : sizes})
File "C:\Python27\lib\site-packages\django\shortcuts.py" in render
  67.             template_name, context, request=request, using=using)
File "C:\Python27\lib\site-packages\django\template\loader.py" in render_to_string
  99.         return template.render(context, request)
File "C:\Python27\lib\site-packages\django\template\backends\django.py" in render
  74.         return self.template.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  209.                     return self._render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in _render
  201.         return self.nodelist.render(context)
File "C:\Python27\lib\site-packages\django\template\base.py" in render
  903.                 bit = self.render_node(node, context)
File "C:\Python27\lib\site-packages\django\template\debug.py" in render_node
  79.             return node.render(context)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
  507.                         six.reraise(*exc_info)
File "C:\Python27\lib\site-packages\django\template\defaulttags.py" in render
  493.             url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in reverse
  579.     return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
File "C:\Python27\lib\site-packages\django\core\urlresolvers.py" in _reverse_with_prefix
  496.                              (lookup_view_s, args, kwargs, len(patterns), patterns))

Exception Type: NoReverseMatch at /store/storeView/zara/
Exception Value: Reverse for 'storeView' with arguments '()' and keyword arguments '{u'user': ''}' not found. 2 pattern(s) tried: ['store/storeView/(?P<user>[\\w-]+)/$', 'store/storeView/(?P<user>[\\w-]+)/$']

2 个答案:

答案 0 :(得分:1)

所以你要做的就是要将AJAX响应与for循环合并,所以你需要它由Django处理。唯一的方法是返回render()响应而不是JSONResponse,然后将其附加到您的html。例如:

创建一个名为_store-form.html的新HTML文件:

<form id="form" action="{% url 'storeView'  user=store.user %}" method="post"  />
                  {% csrf_token %}          

                  <div class="increment">
                  {% for size in sizes %}

                  <strong class="pull-left">{{size}}:</strong> 
                  <input type = "number" name="quantity" value="{{product.quantity}}">
                  <input type = "hidden" name = "size" value="{{size}}">
                  <input type = "hidden" name = "productid" value = "                              {{product.id}}">
                   {% endfor %}
                  </div>
                  <input type="submit" value="submit" id="submit"/>
</form>

在views.py中,而不是最后一行return JsonResponse(data)

return render(request, '_store-form.html', {'sizes': sizes})

现在修改你的JS,将新返回的html附加到你的页面中:

<script type="text/javascript">
    function getStoreView(event, productId) {
        event.preventDefault();   
        var data = {
           productId : productId
        }
        // Send productId as query param of url
        $.ajax({        
            type: "GET",
            url: "{% url 'storeView'  user=store.user %}",
            data: data,
            success: function(data) {
              $('body').append(data);
            },

            error: function(response, error) {
                alert(error);  
            }
        });
    };
</script>

答案 1 :(得分:0)

Django模板变量从views.py传递到上下文,而ajax从其他地方获取值。 Django模板变量和javascript变量是两个不同的东西,你不能指望它们一起工作。您需要使用javascript手动呈现表单。有关详细信息,请查看jquery doc