为什么 Mozilla 的这个 XMLHttpRequest 示例在 Firefox 3 中不起作用?

2023-05-14前端开发问题
16

本文介绍了为什么 Mozilla 的这个 XMLHttpRequest 示例在 Firefox 3 中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试从 Mozilla 获取使用 REST Web 服务以在 Firefox 3.0.10 下工作的示例代码.以下代码在 Firefox 中不起作用,但在 IE 8 中起作用!

I'm trying to get the sample code from Mozilla that consumes a REST web service to work under Firefox 3.0.10. The following code does NOT work in Firefox but does in IE 8!

  1. 为什么这不起作用?
  2. IE 8 是否支持 XMLHttpRequest?我见过的大多数例子都使用 ActiveX分配.我应该做什么?XMLHttpRequest 似乎更加标准化.

示例:

var req = new XMLHttpRequest();
req.open('GET', 'http://localhost/myRESTfulService/resource', false);    // throws 'undefined' exception
req.send(null);
if(req.status == 0)
  dump(req.responseText);

open 语句引发异常,描述为未定义".这很奇怪,因为我分配了 req 对象,在 Firefox 中运行它,并在调用 open 之前检查以确保它已定义(它说它是对象"类型).

The open statement is throwing an exception with the description 'undefined'. This is strange as I allocate the req object, am running it in Firefox, and checked to make sure it is defined before calling open (which it says it is of type 'object').

我也尝试过异步版本,但没有成功.

I've also tried the asynchronous version of this with no luck.

编辑 2:以下是我最近的代码:

function createRequestObject() {
    if( window.XMLHttpRequest ) {
        return new XMLHttpRequest();
    }
    else if( window.ActiveXObject ) {
        return new ActiveXObject( "Microsoft.XMLHTTP" );
    }

    return null;
}

function handleResponse( req ) {
    document.writeln( "Handling response..." );   // NEVER GETS CALLED
    if( req.readyState == 0 ) {
        document.writeln( "UNITIALIZED" );
    }
    else if( req.readyState == 1 ) {
        document.writeln( "LOADING" );
    }
    else if( req.readyState == 2 ) {
        document.writeln( "LOADED" );
    }
    else if( req.readyState == 3 ) {
        document.writeln( "INTERACTIVE" ); 
    }
    else if( req.readyState == 4 ) {
        document.writeln( "COMPLETE" );
        if( req.status == 200 ) {
            document.writeln( "SUCCESS" );
        }
    }
}

document.writeln( "" );
var req = createRequestObject();

try {
    document.writeln( "Opening service..." );
    req.onreadystatechange = function() { handleResponse( req ); };
    req.open('POST', 'http://localhost/test/test2.txt', true);  // WORKS IN IE8 & NOT FIREFOX


    document.writeln( "Sending service request..." );
    req.send('');

    document.writeln( "Done" );
}
catch( err ) {
    document.writeln( "ERROR: " + err.description );
}

编辑 3: 好的,我在 jQuery 中重新设计了这个.jQuery 在 IE 中运行良好,但从 Firefox 运行时会抛出未定义".我仔细检查并在 Firefox 中打开了启用 JavaScript" - 似乎在所有其他网页中都可以正常工作.下面是jQuery代码:

EDIT 3: Alright, I reworked this in jQuery. jQuery works great in IE but it throws 'Undefined' when running from Firefox. I double checked and 'Enable JavaScript' is turned on in Firefox - seems to work fine in all other web pages. Below is the jQuery code:

function handleResponse( resp ) {
    alert( "Name: " + resp.Name );
    alert( "URL: " + resp.URL );
}

$(document).ready( function() {
    $("a").click( function(event) {

        try {
            $.get( "http://localhost/services/ezekielservices/configservice/ezekielservices.svc/test", 
                   "{}",
                   function(data) { handleResponse( data ); },
                   "json" );
        } 
        catch( err ) {
            alert("'$.get' threw an exception: " + err.description);
        }

        event.preventDefault();
    });
} );    // End 'ready' check

解决方案总结:

好的,网络课101.我的问题确实是跨域的.我正在查看未发布的网站(仅在文件系统上),该网站正在访问已发布的服务.当我在同一个域下发布我的网站时,它起作用了.

Alright, web lesson 101. My problem was indeed cross-domain. I was viewing my site unpublished (just on the file system) which was hitting a published service. When I published my site under the same domain it worked.

这也带来了 IE 和 Firefox 之间的一个重要区别.当IE遇到这种情况时,会提示用户是否接受跨域调用.Firefox 抛出异常.虽然我可以有一个例外,但更具描述性的例外会有所帮助.

Which also brings up an important distinction between IE and Firefox. When IE experiences this scenario, it prompts the user whether or not they accept the cross-domain call. Firefox throws an exception. While I'm fine with an exception, a more descriptive one would have been helpful.

感谢所有帮助过我的人.

Thanks for all those who helped me.

推荐答案

除非'http://www.mozilla.org/' 是此请求的来源域,由于同源策略,这将不起作用

unless 'http://www.mozilla.org/' is the domain from which this request originates, this wont work because of same origin policy

好的,好的状态是 200,而不是 0.

edit: Ok, a good status is 200, not 0.

查看 http://dogself.com/telluriumTest/ 并点击stackoverflow 测试".它使用您的代码并正常工作.

see http://dogself.com/telluriumTest/ and click on "stackoverflow test". its using your code and working.

特别是这段代码:

function test(){
    var req = new XMLHttpRequest();
    req.open('GET', 'index2.htm', false);    
    req.send(null);
    if(req.status == 200)
    alert("got some stuff back:"+req.responseText);
}

这篇关于为什么 Mozilla 的这个 XMLHttpRequest 示例在 Firefox 3 中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

ajax请求获取json数据并处理的实例代码
ajax请求获取json数据并处理的实例代码 $.ajax({ type: 'GET', url: 'https://localhost:44369/UserInfo/EditUserJson',//请求数据 data: json,//传递数据 //dataType:'json/text',//预计服务器返回的类型 timeout: 3000,//请求超时的时间 //回调函数传参 suc...
2024-11-22 前端开发问题
215

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 实现实时刷新一个外部的div
主页面上显示了一个合计,在删除和增加的时候需要更改这个总套数的值: //html代码div class="layui-inline layui-show-xs-block" style="margin-left: 10px" id="sumDiv"spanSOP合计:/spanspan${totalNum}/spanspan套/span/div 于是在我们删除这个条数据后,...
2024-11-14 前端开发问题
156

layui 单选框、复选框、下拉菜单不显示问题如何解决?
1. 如果是ajax嵌套了 页面, 请确保 只有最外层的页面引入了layui.css 和 layui.js ,内层页面 切记不要再次引入 2. 具体代码如下 layui.use(['form', 'upload'], function(){ var form = layui.form; form.render(); // 加入这一句});...
2024-11-09 前端开发问题
313

layui laydate日期时间范围,时间默认设定为23:59:59
在Layui中,如果你想设置日期时间选择器(datetime)的默认结束时间为当天的23:59:59,你可以使用如下代码: laydate.render({ elem: '#test10' ,type: 'datetime' ,range: true ,max: '{:date("Y-m-d 23:59:59")}' ,ready: function(date){ $(".layui-laydat...
2024-10-24 前端开发问题
279

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301