[英]XMLHttpRequest() send NS_ERROR_FAILURE for localhost with absolute OR relative path
我在Firefox 31 ESR中收到以下錯誤:
錯誤:NS_ERROR_FAILURE:
源文件:
以下是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
'standard'
我查了幾十頁,其中大多數都在Stack上,問題全都關閉了。
我沒有跨網站腳本的意圖。
我沒有改變method
。
我沒有使用不同的協議(所有HTTP,而不是HTTPS)。
我沒有使用任何子域名。
我從不依賴或削弱我的代碼框架。
我不在乎 ,如果URL 必須是絕對或相對的,我只需要它的工作。
這是一個內聯網網站。
服務器和客戶端都在同一台計算機。
原始URL的格式為: http://localhost/Client/standard/?http-query
目標URL是http://localhost/Client/standard/
。
Apache Access日志顯示請求通過並返回HTTP 200。
open
后立即發出alert()
onreadystatechange
的狀態都沒有記錄在控制台中。
調用ajax
函數時, 不需要設置所有參數。
我錯過了什么?
你正在為同一個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);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.