简体   繁体   中英

ajax code returning ProgressEvent object rather than my template data

I'm trying to improve the UX on a few pages by adding some ajax. I have an ajax request:

var xhr = new XMLHttpRequest();
xhr.open('POST', '/search/', true);
xhr.onload = function(data){
   document.getElementById("search-results-container").innerHTML = data; 
}
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send(form_data);

This isn't giving me the rendered template from my django development server. Instead I get [object ProgressEvent] in my #search-results-container div. The django view renders correctly if I submit the request synchronously.

I'm probably completely misunderstanding the spec , but aren't I supposed to get the template data + http headers straight back from the server? What have I done wrong here?

The event handlers for XHR events are passed event objects. Newer browsers support the ProgressEvent API. Those won't give you the data from the request, however; for that you'll need to retain access to the XHR object itself. The .responseText and (if appropriate) the .responseXML properties will contain your response content once the HTTP request has actually completed (which, in your "load" handler, it will have).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM