我在 Firefox 31 ESR 中收到以下错误:
Error: NS_ERROR_FAILURE:
Source file:
这是来自 Internet Explorer 11 的相同内容:
SCRIPT5022: InvalidStateError
这是调用 AJAX 函数的脚本:
ajax('post','standard/','part='+p+'&price='+q,'sequel_sub_object_key');
这是我的 AJAX 函数:
function ajax(method,url,param_id_container_pos,id_container,id_focus,sequel)
{
var methods = Array('get','head','post');
if (window.XMLHttpRequest && in_array(method,methods))
{
xhr = new XMLHttpRequest();
xhr.open(method,url,true);//Error triggers here for localhost.
if (method=='post')
{
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send(param_id_container_pos);
}
xhr.send(null);
xhr.onreadystatechange = function()
{console.log('xhr.readyState = '+xhr.readyState);
if (xhr.readyState=='4')
{
alert('xhr.responseText = '+xhr.responseText);
}
}
}
显然 Firefox 和 IE 非常模糊地认为我正在执行跨站点脚本...在 localhost 上?
对于 URL,我尝试传递绝对路径和相对路径:
document.getElementsByTagName('base')[0].href+'standard/'
window.location.href
'标准'
我查了几十页,其中大部分都在 Stack 上,问题都没有了。
我对跨站点脚本的意图为零。
我不会更改
方法
。我没有使用不同的协议(protocol)(都是 HTTP,不是 HTTPS)。
我没有使用任何子域。
我从不依赖框架或用框架削弱我的代码。
我不关心 URL 必须是绝对的还是相对的,我只是需要它来工作。
这是一个内联网网站。
服务器和客户端都是同一台计算机。
原始 URL 的格式为:
http://localhost/Client/standard/?http-query
目标 URL 是
http://localhost/Client/standard/
。Apache Access 日志显示请求通过并返回 HTTP 200。
在
open
之后立即发出 控制台中没有记录
onreadystatechange
的任何状态。在调用
ajax
函数时,并非所有参数都需要设置。
alert()
我错过了什么?
最佳答案
您正在为同一个 XHR 对象调用 send()
两次,这可能是错误的来源,因为这会触发 InvalidStateError
,因为对象不是再打开,已经在发送了。
function ajax(method, url, param_id_container_pos, id_container, id_focus, sequel) {
....
if (method == 'post') {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(param_id_container_pos); // you're sending here
}
xhr.send(null); // and then again here, which triggers an error
..........
此外,您通常应该对要发送的数据进行 url 编码
var data = 'part=' + encodeURIComponent(p) +'&price=' + encodeURIComponent(q);
ajax('post', 'standard/', data, 'sequel_sub_object_key');
一起
var data = 'part=' + encodeURIComponent(p) +'&price=' + encodeURIComponent(q);
ajax('post', 'standard/', data, 'sequel_sub_object_key');
function ajax(method, url, param_id_container_pos, id_container, id_focus, sequel) {
var methods = ['get', 'head', 'post'];
if (window.XMLHttpRequest && methods.indexOf(method) != -1) {
var xhr = new XMLHttpRequest();
xhr.open(method, url, true);
if (method == 'post') {
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send(param_id_container_pos);
} else {
xhr.send(null);
}
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert('xhr.responseText = ' + xhr.responseText);
}
}
}
}
关于javascript - XMLHttpRequest() 为具有绝对或相对路径的本地主机发送 NS_ERROR_FAILURE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29631499/