2013-07-04 87 views
0

我有一個$ .ajax請求,並且當我發送響應數據時成功:function(data),我獲取數據但由於某種原因,我無法在If語句中使用它:JQuery .ajax數據未定義

$.ajax({ 
     type: "POST", 
     url: "control.php", 
     data: {"txtNumFattura" : $("#txtNumFattura").val(), 
      "txtDataFattura": $("#txtDataFattura").val()}, 

     success: function(data) { 
     console.log(data); 
     if (data == 'OK') { 
      console.log("Chiave non ancora utilizzata"); 
      $("#submitMyForm").removeAttr("disabled"); 
     } 
     else if(data == 'KO') { 
      $("#mySubmitForm").attr("disabled","disabled"); 
      console.log("Chiave Utilizzata"); 
     }; 
     } 
    }); 

例如console.log給我「OK」或「KO」,但好像它不讀取它在if語句中。

+0

什麼樣的數據,你在迴應期待? – kunal18

+0

它只是在響應「確定」,如果插入的值沒有被用作我的表中的主鍵。 – Roomka

回答

0

嘗試

if(data.toLowerCase().indexOf('ok') != -1){ 
    // ok was found 
} else if (data.toLowerCase().indexOf('ko') != -1) { 
    // ko was found 
} else { 
    // neither was found 
} 
+0

謝謝德文,它幫助! 請問你能解釋一下爲什麼以前不行嗎?! – Roomka

+0

使用indexOf將搜索整個字符串中的任何ok或ko是否存在任何空格或任何其他字符。使用toLowerCase()只是爲了確保無論您如何鍵入它Ok,OK,oK,ok會發現它。 –

+0

@ user2551659不要忘記接受這個答案,如果它幫助你:) –

0

在OK或KO之後可能會有額外的空白。使用

console.log("*" + data + "*"); 

如果有可以使用replace()來刪除這些。例如,

data = data.replace(/\s/g, ""); 

\s是一個空白字符和 'G' 是指在全球範圍。

0

如果您確信它可以讓你確定或KO,你可以試試這個:

if ($.trim(data) === 'OK') { 
    console.log("Chiave non ancora utilizzata"); 
    $("#submitMyForm").removeAttr("disabled"); 
} else if($.trim(data) === 'KO') { 
    $("#mySubmitForm").attr("disabled","disabled"); 
    console.log("Chiave Utilizzata"); 
}; 
+0

其實這也有效!不知道爲什麼,但由於某種原因,它把一個額外的空白。 – Roomka