简体   繁体   English

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

[英]Why is this XMLHttpRequest sample from Mozilla is not working in Firefox 3?

I'm trying to get the sample code from Mozilla that consumes a REST web service to work under Firefox 3.0.10.我正在尝试从 Mozilla 获取示例代码,该代码使用 REST Web 服务以在 Firefox 3.0.10 下工作。 The following code does NOT work in Firefox but does in IE 8!以下代码在 Firefox 中不起作用,但在 IE 8 中起作用!

  1. Why is this not working?为什么这不起作用?
  2. Does IE 8 have support for XMLHttpRequest? IE 8 是否支持 XMLHttpRequest? Most examples I've seen use the ActiveX allocation.我见过的大多数示例都使用 ActiveX 分配。 What should I be doing?我该怎么办? XMLHttpRequest seems more standardized. XMLHttpRequest 似乎更加标准化。

Sample:样本:

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);

The open statement is throwing an exception with the description 'undefined'. open 语句抛出一个描述为“未定义”的异常。 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').这很奇怪,因为我分配了 req 对象,正在 Firefox 中运行它,并检查以确保它在调用 open 之前已定义(它说它是“对象”类型)。

I've also tried the asynchronous version of this with no luck.我也试过异步版本,但没有运气。

EDIT 2: Below is my most recent code:编辑 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 );
}

EDIT 3: Alright, I reworked this in jQuery.编辑 3:好的,我在 jQuery 中重新编写了它。 jQuery works great in IE but it throws 'Undefined' when running from Firefox. jQuery 在 IE 中运行良好,但在 Firefox 中运行时会抛出“未定义”。 I double checked and 'Enable JavaScript' is turned on in Firefox - seems to work fine in all other web pages.我再次检查并在 Firefox 中打开了“启用 JavaScript” - 似乎在所有其他网页中都可以正常工作。 Below is the jQuery code:下面是jQuery代码:

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

Summary of Solution:解决方案总结:

Alright, web lesson 101. My problem was indeed cross-domain.好的,网络课程 101。我的问题确实是跨域的。 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.当我在同一个域下发布我的网站时,它起作用了。

Which also brings up an important distinction between IE and Firefox.这也带来了 IE 和 Firefox 之间的重要区别。 When IE experiences this scenario, it prompts the user whether or not they accept the cross-domain call.当IE遇到这种情况时,会提示用户是否接受跨域调用。 Firefox throws an exception. Firefox 抛出异常。 While I'm fine with an exception, a more descriptive one would have been helpful.虽然我没有例外,但更具描述性的描述会有所帮助。

Thanks for all those who helped me.感谢所有帮助过我的人。

unless ' http://www.mozilla.org/ ' is the domain from which this request originates, this wont work because of same origin policy除非“ http://www.mozilla.org/ ”是发起此请求的域,否则由于同源策略,这将不起作用

edit: Ok, a good status is 200, not 0.编辑:好的,好的状态是 200,而不是 0。

see http://dogself.com/telluriumTest/ and click on "stackoverflow test".请参阅http://dogself.com/telluriumTest/并单击“stackoverflow 测试”。 its using your code and working.它使用您的代码和工作。

specifically this code:特别是这段代码:

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);
}

dont use onreadystatechange when sending synchronous request ('false'), put the handler right after the send() function.发送同步请求 ('false') 时不要使用 onreadystatechange,将处理程序放在 send() 函数之后。 It seems FF doesnt execute the onreadystatechange function if request is synchronous.如果请求是同步的,FF 似乎不会执行 onreadystatechange 函数。

http://support.mozilla.com/tiki-view_forum_thread.php?locale=ca&comments_parentId=124952&forumId=1 http://support.mozilla.com/tiki-view_forum_thread.php?locale=ca&comments_parentId=124952&forumId=1

Even I had same problem and it was silly mistake which we do not focus on the code was working fine in IE but had problems in Chrome and Firefox即使我也有同样的问题,这是一个愚蠢的错误,我们不关注代码在 IE 中运行良好,但在 Chrome 和 Firefox 中出现问题

Initilly we used Type="submit" instead of type="button" though the we did not have any functionality problems like updating the tables but we were getting HTTP: error 0 in the alert box when I alerted req.responseText Using the below code solved my problem最初我们使用Type="submit"而不是type="button"虽然我们没有任何功能问题,例如更新表格,但是当我使用以下代码提醒req.responseText时,我们在警告框中收到HTTP: error 0解决了我的问题

input type="button" name="btnEdit5" id="btnEdit5" value="Confirm" onClick="show_confirm()" 

I highly recommend the asynchronous way to do it, one function kicks off the request and another function handles the response.我强烈推荐异步方式来做到这一点,一个函数启动请求,另一个函数处理响应。

function makeRequest() 
{
   var httpRequest;
   if (window.XMLHttpRequest) // firefox etc 
   {
       httpRequest = new XMLHttpRequest();
   } else if (window.ActiveXObject) { // ie
       httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
   }
   httpRequest.onreadystatechange = function(){handleResponse(httpRequest)};
   httpRequest.open('POST','http://localhost/test/test2.txt',true);
   httpRequest.send('');
}


function handleResponse(request)
{
    if(request.readyState == 4) {
        if(request.status == 200) {
        // handling code here
            // request.responseText is the string returned
        }
    }
}

This is the basic format for ajax calls we use where I work, this should work the same for Firefox, IE, and Safari.这是我们在我工作的地方使用的 ajax 调用的基本格式,这应该适用于 Firefox、IE 和 Safari。

Side note: do you have firebug?旁注:你有萤火虫吗? its a great resource for troubleshooting javascript.它是解决 javascript 故障的绝佳资源。

EDIT: Try this code instead:编辑:试试这个代码:

<html>
<head>
<script>
function out(outStr) // cheap and dirty output function
{
    document.getElementById("out").innerHTML += "<br>" + outStr;
}

function handleResponse(req) {
    if( req.readyState == 0 ) {
        out("UNITIALIZED");
    }
    else if( req.readyState == 1 ) {
        out("LOADING");
    }
    else if( req.readyState == 2 ) {
        out("LOADED");
    }
    else if( req.readyState == 3 ) {
        out("INTERACTIVE"); 
    }
    else if( req.readyState == 4 ) {
        out("COMPLETE");
        if( req.status == 200 ) {
            out(req.responseText);
        }
    }
}

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

function makeRequest()
{
    var req = createRequestObject();

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


        out("Sending service request...");
        req.send('');

        out("Done");
    }
    catch( err ) {
        out("ERROR: " + err.description);
    }
}
</script>
</head>
<body>
<div onclick="makeRequest();">test<br></div>
<div id="out">Output Here</div>
</body>
</html>

point: http://localhost/test/test2.txt to an existing file on your server.指向: http://localhost/test/test2.txt到您服务器上的现有文件。

Not sure exactly what is going wrong with your code, but it is writing straight to document which appears to be hosing all of the code already written there.不确定您的代码到底出了什么问题,但它直接写入文档,这似乎包含了已经在那里编写的所有代码。 in this version I am writing to a div instead.在这个版本中,我改为写入 div。

也不确定这里发生了什么,但只是想让大家知道 Mozilla 文档中的某个人正在关注此内容,以准备好调整文档,如果发现有必要的话。

Other than all the obvious errors on the client side, the main reason for this is that gecko engine looks for the Access-Control-Allow-Origin in the header from the servlet.除了客户端的所有明显错误之外,造成这种情况的主要原因是 Gecko 引擎在 servlet 的标头中查找 Access-Control-Allow-Origin。 If it does not find it, it will abort the communication and you get a status=0 and statusText=null.如果它没有找到它,它将中止通信,您将获得 status=0 和 statusText=null。 Also, the moz-nullprincipal in xml parsing error.此外,xml 解析错误中的 moz-nullprincipal。 All of this stuff is very misleading.所有这些东西都非常具有误导性。 All you need to resolve this problem is:解决此问题所需要做的就是:

response.setHeader("Access-Control-Allow-Origin","*");

In the servlet code and life will be good :-)在 servlet 代码和生活中会很好:-)

Replace the line更换线路

req.open('POST', 'http://localhost/test/test2.txt', true); // WORKS IN IE8 & NOT FIREFOX

with

req.open('GET', 'http://localhost/test/test2.txt', true); // WORKS IN IE8 & NOT FIREFOX

I ran into the same problem.我遇到了同样的问题。 The reason that IE works and no other browsers is because IE lets you open the file with a URL like "C:\\xampp\\htdocs\\project3\\project3.html" Other browsers will change this to a URL like "file:///C:/xampp/htdocs/project3/project3.html". IE 可以工作而其他浏览器无法运行的原因是因为 IE 允许您使用类似“C:\\xampp\\htdocs\\project3\\project3.html”的 URL 打开文件其他浏览器会将其更改为类似“file:///”的 URL C:/xampp/htdocs/project3/project3.html”。 Since the domain of the PHP file has to be the same as the domain of the javascript file IE works, but other browsers don't.由于 PHP 文件的域必须与 IE 工作的 javascript 文件的域相同,但其他浏览器则不然。 Make sure that you use a URL like "http://localhost/project3/project3.html".确保您使用类似“http://localhost/project3/project3.html”的 URL。 Please note the use of localhost.请注意 localhost 的使用。 Also make sure that in your javascript call you are calling the PHP file through localhost.还要确保在您的 javascript 调用中,您通过 localhost 调用 PHP 文件。

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

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