2013-10-31 60 views
-1

我试图用错误处理try/catch来捕捉Ajax错误,但它不工作。这里是我的代码:Javascript错误处理不起作用

var ajaxrequest=null 
if (window.ActiveXObject){ 
try { 
    ajaxrequest=new ActiveXObject("Msxml2.XMLHTTP") 
} 
catch { 
    try{ 
    ajaxrequest=new ActiveXObject("Microsoft.XMLHTTP") 
    } //end inner try 
    catch { 
    alert("NOT WORKING!!") 
    } //end inner catch 
} //end outer catch 
} 
else if (window.XMLHttpRequest) // if Mozilla, Safari etc 
ajaxrequest=new XMLHttpRequest() 

ajaxrequest.open('GET', 'inventory.php', true) //do something with request 

我做错了什么?

+2

也许它只是不会抛出一个例外...... – 2013-10-31 19:50:38

回答

1

您错过了要捕捉的参数。它应该是catch(ex)。以下是修复:

if (window.ActiveXObject){ 
try { 
    ajaxrequest=new ActiveXObject("Msxml2.XMLHTTP") 
} 
catch (ex){ 
    try{ 
    ajaxrequest=new ActiveXObject("Microsoft.XMLHTTP") 
    } //end inner try 
    catch (ex){ 
    alert("NOT WORKING!!") 
    } //end inner catch 
} //end outer catch 
} 
+0

就是这样!我真的需要多睡一会儿!谢谢! – devXen

0

使用catch子句w/o任何参数导致SyntaxError: Unexpected token {。捕捉异常的正确方法是这样的:

try { 
    // some code which probably causes exception 
} catch(e) { 
    // do something with the exception 
} 

检查出exception handling in JavaScript的文档。