带有If语句的Ajax ResponseText

时间:2013-10-23 23:44:37

标签: ajax

我正在使用Ajax通过php文件修改mysql数据库中的一些数据。我编写了代码,以便php文件回显“OK”或“ERROR”。我已经检查了警报(ret)并且工作正常。但问题在于if(ret ==“OK”)。它没有进入这个声明。有人可以帮帮我吗?

xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
   if (xmlhttp.readyState==4 && xmlhttp.status==200){
       document.getElementById('Store_cards_action_form_close').click();
       ret = xmlhttp.responseText;
       if (ret=="OK"){
           alert("Congratulations. Transaction Successful.");
           document.location.reload();      
       }
       else{
           alert("You have Insufficient Coins to buy this Card!");
       }
   }
}
xmlhttp.open("GET","script_card_transaction.php?" + para,true);
xmlhttp.send();   

1 个答案:

答案 0 :(得分:0)

正如我的评论中所提到的,您的回复文字周围可能有一些空白字符。您可以trim响应文本,或者使用JSON格式的字符串。例如,在PHP文件中

header('Content-type: application/json');
echo json_encode(array('status' => $status)); // where $status is 'OK' or 'ERROR'
exit;

然后,将其解析为JS中的JSON

var ret = JSON.parse(xmlhttp.responseText);
if (ret.status == 'OK') {
    // etc

我可能会更进一步,使用比字符串“OK”和“ERROR”更不明确的东西。例如

echo json_encode(array('success' => $isSuccess)); // where $isSuccess is a boolean (true or false)

和JS ......

if (ret.success) {
    // etc
相关问题