我在读取响应键时遇到问题,然后在出现错误时输出消息。
如果没有错误,我可以输出"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()));
}
?>
请告知
答案 0 :(得分:0)
我认为你在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>