问题
I currently have this Javascript in a file named getresults.js:
function getItems(str)
{
if (str=="")
{
document.getElementById("getItems").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("getItems").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","/include/retrieveitems.php?q="+str,true);
xmlhttp.send();
}
It's called upon by this event:
onclick="getItems('all')"
It works perfectly in Firefox, IE, Chrome.. but Opera refuses to work. A very small percentage of my visitors are Opera users, but still.. I'd rather have it work. A live url can be found here: http://tf2g.com/gallery
If anyone can help, much obliged!
回答1:
The reason this fails is that the event handler is not calling your getItems() method at all. It sees the document.getItems() method from Opera's Microdata support ( http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html ) and calls that instead. It's a question of JavaScript scope: both the element itself and its document is in scope, so methods/properties defined here will be able to hide methods / properties you define in the global scope.
Be happy that Opera implemented Microdata early so you noticed this :)
The simplest fix is to rename your function to avoid name collision with Microdata. You can also use addEventListener() instead of writing onclick="" in the markup - if you do the scope of the function is the scope it is created in, so you don't run into such gotchas.
window.addEventListener('load', function(){
for( var i=0,l;l=document.links[i]; i++ )if( l.hash){
l.addEventListener( 'click', function(){
getItems(this.hash.substr(1));
}, false);
}
}, false);
回答2:
I debugged your link a bit and found out that there's no problem with the AJAX request. In fact, there's an unhandled exception in jquery.min.js file which prevents other javascript code from running.
Steps I did: I opened Opera DragonFly (Ctrl+Shft+I), which is firebug-a-like and refresh the page. I inserted break-points in 'getItems()' and saw that the code didn't reach there. Via Dragonfly console I wrote "getItems('all');" and the ajax went as expected.
O
来源:https://stackoverflow.com/questions/12097176/javascript-ajax-not-working-in-opera-works-perfect-in-ff-ie-chrome