0

応答のキーを読み取り、エラーが発生したときにメッセージを出力するのに問題があります。

エラーがなければ、出力できます"Data says: {"msg":"I am BB"}"

しかし、を true に変更すると、「エラーは次のように表示されます: {"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())); 
    }
?>

お知らせ下さい

4

1 に答える 1