2014-08-28 40 views
4

我有將電子郵件發送到的地方,並接收來自從與類型JSON對象服務器的響應=成功或錯誤的AJAX功能的比較JavaScript的奇怪串

$("#submit_btn").click(function(event) { 
    event.preventDefault(); 

    var post_data = { 
     'email': $("#email").val() 
    }; 
    $.post("sendEmail.php", post_data).done(function(response){ 
     if(response.type == 'success'){ 
      $("#sentmail").fadeIn("slow") 
      setTimeout(function(){ 
       $("#mail").val("Enter your email here"); 

       $("#sentmail").fadeOut("slow") 
      },3000); 
     } 
     else{ 
      $("#sentmailfail").fadeIn("slow") 
      setTimeout(function(){ 
       $("#mail").val("Enter your email here"); 

       $("#sentmailfail").fadeOut("slow") 
      },3000); 
     } 
    },"json") 
}); 

有趣的是,如果我console.log(response)我得到例如{"type":"success","desc":"something"}再經過直說console.log((response.type == "error")) // TRUE

如果我從響應安慰日誌,並將其分配給一個變量,例如a = {"type":"success","desc":"something"}然後a.type == "error"是假的。

有人可以解釋這一點嗎?

+2

沒有任何共同之處。 – 2014-08-28 22:01:25

+1

我的問題是*當*你嘗試'console.log(response)'時? – amphetamachine 2014-08-28 22:02:35

+1

'{「type」:「success」'''type ==「error」'呃......你明顯錯過了一些東西,因爲你的例子完全沒有。沒有一個更徹底的例子是不可能的。 – 2014-08-28 22:02:40

回答

4

如果console.log(response)輸出

{"type":"success","desc":"something"} 

然後response是最有可能的還是(含JSON)的字符串和字符串沒有type屬性:

> "foo".type == "error" // `undefined` is never equal to a string 
false 

對象通常看在控制檯中有所不同:

> console.log({"type":"success","desc":"something"}) 
Object {type: "success", desc: "something"} // in Chrome and Firefox at least 

解決方案:第一解析字符串:

response = JSON.parse(response); 

相關的jQuery的:

我注意到,你打算讓jQuery的解析JSON你,但你是路過"json"到錯誤的功能。你必須將它傳遞給$.post(...),不.done(...)

$.post("sendEmail.php", post_data, "json").done(...); 
// instead of 
// $.post("sendEmail.php", post_data).done(..., "json"); 

那麼你不需要手動解析它。


相關:Parse JSON in JavaScript?

+0

我試着手動解析JSON,但它沒有改變任何東西,將「json」移動到.post方法中也沒有做任何事情。我console.log在if語句之前的響應 然後我console.log(response.type)//「錯誤」 然後我console.log(response.type!=「error」)// true – 2014-08-28 22:19:51

+0

什麼'console.log(response.type.length)'輸出? – 2014-08-28 22:20:43

+0

它輸出「找不到未定義的屬性長度」。我只寫了JSON.parse(響應),沒有將它分配給任何問題。謝謝! – 2014-08-28 22:28:57