处理异常:读取键并进行比较,然后输出,否则出错


Handling Exception: Reading the key and compare, then output, otherwise error

我在读取响应的密钥时遇到问题,然后在出现错误时输出消息。

如果没有错误,我可以输出"Data says: {"msg":"I am BB"}"

但当我将更改为true时,我似乎无法输出"Error says:{"errmsg":"Error_BB"}"。问题是我很难读懂钥匙。

main.php

<script type="text/javascript">
var xmlhttp;
if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();
} else {    
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 
}
try
{
    xmlhttp.open("Get", "testBB.php?", true); 
    xmlhttp.send(); 
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {      
            var response = (xmlhttp.responseText);
            console.log('obtained:'+response);
            var keys=[];
            for(var key in response)
                keys.push(key);
            console.log(keys[0].value);
            //var key = Object.getOwnPropertyNames(data);
            //console.log(key);
            if (keys[0].value == "errmsg")// check if msg any errmsg {
                console.log('threw a new error'); 
                throw new Error("Error says: "+response);
            } else {
                console.log('Data says: '+response);
                alert("Data says: "+response);
            }
        }
    }
}
catch(e) {
    alert(e);
}
</script>

testBB.php

<?php
    try {   
        if(true) {
            throw new Exception("Error_BB",1);
            $firephp->error('Error_BB');
        } else {
            $ans = json_encode(array("msg"=>"I am BB"));    
            echo $ans;
            $firephp->warn($ans);   
        }
    }
    catch(exception $e) {
        echo json_encode(array("errmsg"=>$e->getMessage())); 
    }
?>

请告知

我认为您的语法在PHP和JAVASCRIPT之间混淆了。

此外,作用域也被搞砸了,尤其是在javascript中的try-catch中:您还需要在调用.send之前注册onreadystatechange匿名函数,以防在它有机会正确注册如何处理回复之前收到回复。

请尝试此测试脚本,然后将更改应用于代码。

<html>
<head>
    <script type="text/javascript">
    function doit()
    {
        var xmlhttp;
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.open("GET", "testBB.php", true);
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                try {
                    // convert response back to a json object
                    var response = eval ( "(" + xmlhttp.responseText + ")" );
                    if (response.errmsg == "Error_BB") {
                        throw "Error says: "+response.errmsg;
                    } else {
                        console.log('Data says: '+response.errmsg);
                    }
                }
                catch(e) {
                    alert(e);
                }
            }
        }
        xmlhttp.send();
    }
    </script>
</head>
<body>
    <div>Testing XMLHttpRequest</div>
    <button onclick="doit();" >DoIt</button>
<body>
</html>