如何避免在 XMLHttpRequest 调用后自动重新加载页面?
我知道这有点自相矛盾,因为 XMLHttpRequest 不应该重新加载页面,这就是它的全部意义所在.
I know this is a bit paradoxal because XMLHttpRequest shouldn't be reloading the page, and it's the whole point of it.
在 Chrome 最新版本、iOS 上的 Safari 和 Android 上进行了尝试.结果都一样.
Tried in Chrome latest version, Safari on iOS and on an Android. All same result.
我正在通过它发送一个带有文件的表格.效果很好,目标站点正确接收数据并显示它.发回 200,OK".(这是脸书)
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". (It's facebook)
但是我的页面会自动重新加载.就像我使用 HTML 表单和提交按钮提交表单一样.(这是我原来的问题)
But then my page reloads automatically. Just like if I submitted the form using HTML form and a submit button. (Which was my original problem)
这是我的做法,来自 Javascript
Here is how I do it, from 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...
推荐答案
您是否有可能通过提交表单来触发此问题?如果您不在 onsubmit 处理程序中return false
,表单仍然会被提交.
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.
相关文章