为什么我使用Ajax重定向/刷新

时间:2019-05-13 19:55:30

标签: javascript ajax django xmlhttprequest

我尝试将Django与XMLHttpRequest结合使用,尝试提交而不刷新页面。但是在控制台电子邮件中我没有定义错误。

这是我的表单>名称,电子邮件,地址,文本

order_create.html

<h2>Create order</h2>
<form method="POST" id="post_form">
    {% csrf_token %}
    {{form.as_p}}
    <button id="button">Submit</button>
</form>

在尝试将Javascript与XMLHttpRequest一起使用


document.getElementById('post_form').addEventListener('submit', event => {

    event.preventDefault();

    var body = 'name=' + name + "&email=" + email + "&address=" + address + "&text=" + text;


    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/order/', true);
    xhr.send(body); 

    xhr.onload = function() {
        var jsonResp = JSON.parse(this.response);
        if (this.status == 200) {
            alert(jsonResp);
        } else {
            alert('ERROR');
        }
    }

});

urls.py

urlpatterns = [
    url(r'^order/$', views.order_create, name='order_create')
]

views.py

def order_create(request):
    cart = Cart(request)
    if request.method == 'POST':
        form = OrderCreateForm(request.POST)
        response_data = {}
        if form.is_valid():
            order = form.save()
            for item in cart:
                OrderItem.objects.create(
                    order=order,
                    product=item['product'],
                    price=item['price'],
                    quantity=item['quantity']
                )
            cart.clear_session()

        return JsonResponse(json.dumps(response_data), content_type="application/json", safe=False)
    else:
        form = OrderCreateForm()
        return render(request, 'orders/order_create.html', {'cart':cart, 'form':form})

在控制台中未定义错误电子邮件

2 个答案:

答案 0 :(得分:3)

您正在谈论的“重定向/刷新”是表单执行其默认操作:提交表单。这将导致浏览器离开页面,从而阻止JavaScript进一步执行。

为防止这种情况,并使其在提交时运行您的AJAX代码,请使用element.addEventListener()在表单元素上附加一个submit事件。在处理程序中,使用event.preventDefault()阻止表单执行默认的表单提交操作。

referenceToForm.addEventListener('submit', event => {
  // Prevent the default behavior of the element. In the case of forms,
  // the act of submitting form data.
  event.preventDefault()

  // The rest of your event handling code

})

答案 1 :(得分:1)

    <h2>Create order</h2>
     <form method="POST" id="post_form">
        {% csrf_token %}
        {{form.as_p}}
        <button id="button">Submit</button>
     </form>

let form = document.querySelector("form");
form.addEventListener("submit", (event)=>{

   // This will help you to diable the defaut property of the form, And stops refresing on the submit 

   if(event && event.preventDefault){
      event.preventDefault();
   }

   let formData = new FormData(form)

   //This code will iterate data from the input elements from your form
   let postData = {};

   for(let [key, val] of formData.entries()){
    if(val) postData[key] = val;
   }


   postData(event.target.action, postData)
  .then(data => console.log(JSON.stringify(data))) 
  .catch(error => console.error(error));
})

function postData(url = '', data = {}) {
  // Default options are marked with *
    return fetch(url, {
        method: 'POST', // *GET, POST, PUT, DELETE, etc.
        mode: 'cors', // no-cors, cors, *same-origin
        cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
        credentials: 'same-origin', // include, *same-origin, omit
        headers: {
            'Content-Type': 'application/json',
            // 'Content-Type': 'application/x-www-form-urlencoded',
        },
        redirect: 'follow', // manual, *follow, error
        referrer: 'no-referrer', // no-referrer, *client
        body: JSON.stringify(data), // body data type must match "Content-Type" header
    })
    .then(response => response.json()); // parses JSON response into native Javascript objects 
}