2013-11-11 2 views
-1

У меня есть функция javascript, которая включает в себя несколько if else statements по какой-то причине одно из утверждений работает неправильно.Java Script если инструкция не работает

Сценарий:

function makePayment(reservationID) { 
var expirationDate = $("#expirationDate").val(); 
var creditCard = $("#creditcard").val(); 

if (creditCard.length == 16 && expirationDate.length == 4) { 
    var month = ""; 
    var year = ""; 
    month += expirationDate.charAt(0); 
    month += expirationDate.charAt(1); 

    year += expirationDate.charAt(2); 
    year += expirationDate.charAt(3); 

    var monthInt = parseFloat(month); 
    var yearInt = parseFloat(year); 
    var currect; 

    if (monthInt > 0 && monthInt < 13 && yearInt > 12 && yearInt < 24) { 



     $.ajax({ 
      url: "CreditAuthentication", 
      data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate, 
      success: function(responseText) { 
       currect = responseText; 
       console.log(responseText); 
      }, error: function(xhr) { 
       alert(xhr.status); 
      }}); 

     if (currect == true) { 

      // 
      $.ajax({ 
       type: "POST", 
       url: "paymentMethods", 
       data: "type=make&reservationID=" + reservationID, 
       success: function(msg) { 
        console.log("Paymentmade"); 
        alert("Payment made"); 

        //alert(CCA); 
        document.location = "index.jsp#reservation"; 
       } 
      }); 
     } 

     else if(currect === "false") { 
      alert("Please enter valid details. 3rd"); 
     } 
     // 
    } else { 
     alert("Please enter valid details. 2nd"); 
    } 

} else { 
    alert("Please enter valid payment information. 1st"); 
} 
} 

Я проверил в FireBug и возвращаемое значение из моего сервлета правильно и и console.log(responseText); отображает ответ в консоли. Однако по какой-то причине эта часть инструкции не работает и не отображает предупреждения:

if (currect == true) { 

    $.ajax({ 
     type: "POST", 
     url: "paymentMethods", 
     data: "type=make&reservationID=" + reservationID, 
     success: function (msg) { 
      console.log("Paymentmade"); 
      alert("Payment made"); 
      document.location = "index.jsp#reservation"; 
     } 
    }); 

} else if (currect === "false") { 
    alert("Please enter valid details. 3rd"); 
} 

Спасибо заранее!

+2

Возможный дубликат [Как вернуть ответ на вызов AJAX?] (Http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) –

+0

С AJAX 'ниже' не означает' after'. Переменная 'currect' проверяется _before_ Обратный вызов AJAX имеет шанс присвоить ему результат. – raina77ow

+1

Почему, если currect == true ?? и else, если просто сделать if (currect) {} else {} – Ahmad

ответ

0

Пожалуйста, убедитесь, что currect не имеет значения null или undefined, а если нет. сделать 'currect' глобальный, так что может быть, доступную:

var currect; //declare it here 
    $.ajax({ 
      url: "CreditAuthentication", 
      data: "type=reserve&creditCard=" + creditCard + "&expirationDate=" + expirationDate, 
      success: function(responseText) { 
       currect = responseText; 
       console.log(responseText); 
      }, error: function(xhr) { 
       alert(xhr.status); 
      }}); 

тогда, если currect является булевой то попробуйте:

if (currect) { 
    //your code 
} else { 
    //your code 
} 

и если это строка:

if (currect === 'true') { 
    //your code 
} else if(currect === 'false') { 
    //your code 
} 
+0

Даже если это строка, наверняка 'else {...' хватит? – rybo111

+0

Нет в строковом случае он может содержать другие штифты, такие как «правильный» ... –

0

You нужно поместить currect if/else в функцию успеха вашего вызова ajax.

Смежные вопросы