为什么即使我使用Ajax也要加载页面?

时间:2019-07-20 06:20:25

标签: django ajax

def tracker(request):
    if request.method == "POST":
        orderId = request.POST.get('orderId','')
        email = request.POST.get('email','')

        try:
            order = Orders.objects.filter(order_id=orderId, email=email)
            if len(order) > 0:
                update = Updateorder.objects.filter(order_id=orderId)
                updates = []
                for item in update:
                    updates.append({'text':item.update_desc, 'time':item.time_stamp})
                    response = json.dumps(updates, default=str)
                    return HttpResponse(response)
                else:
                    print(len(order))
                    return HttpResponse(f"{len(order)}")
        except Exception as e:
            return HttpResponse(f'exception {e}')
    return render(request,'shop/Tracker.html')
{% extends 'shop/base.html' %} {% block title %}MAC Tracker {% endblock %} {% block body %}


<div class="container">
  <div class="col-md-8 offset-md-2 my-4">
    <h3>Step 1 - Enter your Email address and tracker ID to track your order</h3>

    <form method="post" id="trackerForm" action="#">{% csrf_token %}

      <div class="form-row">
        <div class="form-group col-md-6">
          <label for="name">Tracker ID</label>
          <input type="text" class="form-control" id="orderId" name="orderId" placeholder="Enter tracker ID">
        </div>

        <div class="form-group col-md-6">
          <label for="email">Email</label>
          <input type="email" class="form-control" id="email" name="email" placeholder="Enter Email">
        </div>

      </div>
      <button type="submit" class="btn btn-primary">Track Order</button>
    </form>
  </div>


  <div class="col-md-8 offset-md-2 my-5">
    <h3>Your order status</h3>
    <ul class="list-group" id="items">
      <b>Enter your order Id and Email and click Track Order to find details about your order!</b>
    </ul>

  </div>
</div>

{% endblock %} {% block js %}

<script>
  $('#trackerForm').submit(function(event) {
    $('#items').empty();
    var formData = {
      'orderId': $('input[name=orderId]').val(),
      'email': $('input[name=email]').val(),
      'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
    };
    $.ajax({
        type: 'POST',
        url: '/shop/tracker/',
        data: formData,
        encode: true
      })
      .done(function(data) {
        console.log(data);
        updates = JSON.parse(data);
        if (updates.length > 0 & updates != {}) {
          for (i = 0; i < updates.length; i++) {
            let text = updates[i]['text'];
            let time = updates[i]['time'];
            mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
                    ${text}
                    <span class="badge badge-primary badge-pill">${time}</span>
                </li>`
            $('#items').append(mystr);
          }
        } else {
          mystr = `<li class="list-group-item d-flex justify-content-between align-items-center">
                    Sorry, We are not able to fetch this order id and email. Make sure to type correct order Id and email</li>`
          $('#items').append(mystr);
        }
      });
    event.preventDefault();
  });
</script>

{% endblock %}

当我尝试提交表单时,我正在使用ajax提交表单,它显示错误jquery-3.4.1.js:9837 POST http://127.0.0.1:8000/shop/tracker/ 404(未找到)。

我添加了event.preventDefault();仍然不起作用

$。ajax({             输入:“ POST”,             网址:“ / shop / tracker /”,             数据:formData,             编码:true         })         .done(function(data){             console.log(数据)             更新= JSON.parse(数据);             如果(updates.length> 0&更新!= {}){                 对于(i = 0; i <li class="list-group-item d-flex justify-content-between align-items-center"> ${text} <span class="badge badge-primary badge-pill">${time}</span> </li>                     $('#items')。append(mystr);

我希望html输出在同一页面中,但没有发生任何变化。对于参考views.py和html页面已在以上部分中显示。

1 个答案:

答案 0 :(得分:1)

谢谢stefan和henrik的评论,我刚刚更正了URL,并且页面正常运行。更正的url:'/ shop / tracker'之前是'/ shop / tracker /',末尾多了一个斜杠引起了问题。