在模板中显示JsonResponse数据

时间:2019-05-12 16:46:27

标签: ajax django django-templates django-views

我想在demo.html中发送JsonResponse数据并在其中显示。我的代码有什么问题。请帮我解决。

 function ComAction() {
     let xhr = new XMLHttpRequest(),
     data = new FormData();
     data.append('csrfmiddlewaretoken', getCookie('csrftoken'));
     brands.forEach(function (brand) {
        data.append('brand', brand);
    });

    xhr.open('POST', 'compare_in/', true);
    xhr.onload = function () {
        if (xhr.status === 200) {
            data = JSON.parse(xhr.responseText);
            console.log(data);
            alert('Data received successfully. Brands are ' + data.brands);
            window.location.assign({% url 'demo' %});
        } else if (xhr.status !== 200) {
            alert('Request failed.');
        }
    };
  xhr.send(data);
}

这是我的网址:

urlpatterns = [
path('compare_in/', views.compare, name='compare'),
path('demo/', views.demo, name='demo'),
]

这是我的观点

  def compare(request):
     if request.method == 'POST':
        compare_res = request.POST.getlist('brand')
        d3 = {'brand':{'x', 'y'}, 'color':{'black', 'white'}}
        response_data = {
            'brands': d3,
            'redirect_url': 'http://127.0.0.1:8000/demo/'}
     return JsonResponse(response_data)
  return render(request, 'prodcutSearch/compare_in.html')


  def demo(request):
     return render(request, 'prodcutSearch/demo.html')

0 个答案:

没有答案