te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Why is this XMLHttpRequest sample from Mozilla is not working in Firefox 3? - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is this XMLHttpRequest sample from Mozilla is not working in Firefox 3? - Stack Overflow

programmeradmin3浏览0评论

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. Why is this not working?
  2. Does IE 8 have support for XMLHttpRequest? Most examples I've seen use the ActiveX allocation. What should I be doing? XMLHttpRequest seems more standardized.

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'. 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.

EDIT 2: Below is my most recent code:

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. 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

Summary of Solution:

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.

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.

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. Why is this not working?
  2. Does IE 8 have support for XMLHttpRequest? Most examples I've seen use the ActiveX allocation. What should I be doing? XMLHttpRequest seems more standardized.

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'. 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.

EDIT 2: Below is my most recent code:

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. 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

Summary of Solution:

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.

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.

Share Improve this question edited May 29, 2009 at 16:10 Jordan Parmer asked May 27, 2009 at 15:18 Jordan ParmerJordan Parmer 37.2k30 gold badges99 silver badges120 bronze badges 1
  • i have used your new "slightly modified" code on my server. it works in firefox 3. check it out: dogself./telluriumTest/test.htm i only added better logging and remove that horrible document.write crap. – mkoryak Commented May 27, 2009 at 18:44
Add a ment  | 

8 Answers 8

Reset to default 4

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

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

see http://dogself./telluriumTest/ and click on "stackoverflow test". 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. It seems FF doesnt execute the onreadystatechange function if request is synchronous.

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

I highly remend 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.

Side note: do you have firebug? its a great resource for troubleshooting 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.

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.

not sure what's going on here either, but just wanted you all to know that someone from Mozilla documentation is watching this to be ready to tweak the docs if it turns out to be necessary once this is figured out.

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

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

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

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". 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. Make sure that you use a URL like "http://localhost/project3/project3.html". Please note the use of localhost. Also make sure that in your javascript call you are calling the PHP file through localhost.

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. If it does not find it, it will abort the munication and you get a status=0 and statusText=null. Also, the moz-nullprincipal in xml parsing error. 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 :-)

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
发布评论

评论列表(0)

  1. 暂无评论