1

Ajax を使用して、php ファイルを介して mysql データベースの一部のデータを変更しています。PHPファイルが「OK」または「ERROR」をエコーするようにコードを書きました。alert(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();   
4

1 に答える 1

1

私のコメントで述べたように、応答テキストの周りに空白文字が含まれている可能性があります。応答テキストをトリミングするか、代わりに 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
于 2013-10-23T23:52:13.000 に答える