简体   繁体   English

XMLHttpRequest调用后如何避免自动页面重新加载?

[英]How to avoid automatic page reload after XMLHttpRequest call?

I know this is a bit paradoxal because XMLHttpRequest shouldn't be reloading the page, and it's the whole point of it. 我知道这有点自相矛盾,因为XMLHttpRequest不应该重新加载页面,这是它的全部意义。

Tried in Chrome latest version, Safari on iOS and on an Android. 尝试使用Chrome最新版本,iOS版和Android版Safari。 All same result. 所有相同的结果。

I am sending a form through it, with files. 我正在通过文件发送表格。 Works great, the destination site receive correctly the data, and displays it. 效果很好,目标站点正确接收数据并显示它。 Sends back a 200, "OK". 发回200,“OK”。 (It's facebook) (这是facebook)

But then my page reloads automatically. 但随后我的页面会自动重新加载。 Just like if I submitted the form using HTML form and a submit button. 就像我使用HTML表单和提交按钮提交表单一样。 (Which was my original problem) (这是我原来的问题)

Here is how I do it, from Javascript 我是这样做的,来自Javascript

// Get the form element
var formData = new FormData(document.getElementById("photosubmitform")); 

var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://graph.facebook.com/' + facebookWallId + '/photos', false);
xhr.onload = function(event)
{
    var json = xhr.responseText; // Response, yay!
}
xhr.send(formData); // Sending it, will reload the page on success...

Any chance you're triggering this by submitting a form? 你有机会通过提交表格来触发这个吗? If you don't return false in the onsubmit handler, the form will still be submitted. 如果您未在onsubmit处理程序中return false ,则仍将提交表单。

在表单中观察按钮单击时使用event.preventDefault()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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