2012-10-25 47 views
0

我正在使用Jquery執行POST來驗證我的頁面。

$.post("api/authenticate", {"authkey": authkey}, function(data){ 
    console.log(data); 
    if (data.success === "false") { 
    window.location="/Login.html"; 
    } 
}); 

編輯!

如果身份驗證不成功,我的PHP函數會返回一個JSON對象

{"success":"false"} 

然而,執行console.log(數據)不返回我什麼。儘管我可以在資源中看到迴應。

任何人都知道我該如何解決這個問題?

任何幫助,非常感謝。

回答

1

氟利昂的回答大概作品,這裏是一個選擇,請嘗試強制dataType到JSON。

// This is the signature for $.post 
jQuery.post(url [, data] [, success(data, textStatus, jqXHR)] [, dataType]) 

$.post("api/authenticate", {"authkey": authkey}, function(data){ 
    console.log(data); 
    if (data.success === "false") { 
     window.location="/Login.html"; 
    } 
}, "json"); 

另一個想法是要確保您的服務器響應2xx狀態。如果您返回不同的狀態,jQuery將不會嘗試讀取響應。這反而查找傳遞給http://api.jquery.com/jQuery.ajax/

jQuery.ajax("api/authenticate", { 
    data: {"authkey": authkey}, 
    dataType: 'json', 
    statusCode: { 
     306: function(jqXhr, errorType) { 
      alert('Could not login') 
      // If you still want to access the response, it's accessible as raw text 
      // If it's JSON, you have to parse it. 
      alert (jqXhr.responseText); 
     } 
    } 
}); 
+0

我意識到功能(數據)只有在api/authenticate成功時纔會進入。任何想法我能做些什麼來獲得數據時,API調用不成功? – Wilson

+0

ahhh。我發現什麼是錯的。在我的PHP函數中,即使我返回了一個JSON,但我還是以306頁的錯誤返回了它。因此,post方法拒絕了迴應並認爲它不成功。我現在能夠閱讀回覆。謝謝! – Wilson

+0

@Wilson好的,既然你接受了這個答案,我會將這些信息添加到答案本身中,以便將來用戶更容易獲得 –

-2

你需要遍歷你的數據作爲一個數組,例如data[0]通過for循環或while循環

+0

遺憾的statusCode選項設置狀態碼處理。數據[0]給了我「未定義」 – Wilson

+0

console.log(數據)返回一個空白值。即使它是一個數組,它也不應該是空的。 –

1

如果您期待JSON,請使用$ .getJSON。它會將您的響應解析爲JSON對象。

$.getJSON("api/authenticate", {"authkey": authkey}, function(jsonObj){ 
    console.log(jsonObj); 
    if (jsonObj.success === "false") { 
     window.location="/Login.html"; 
    } 
}); 

http://api.jquery.com/jQuery.getJSON/

+0

是$ .getJson使用get或post方法嗎? – Wilson

+0

它使用GET。您可以在答案中的鏈接中看到更多詳細信息。 –

+0

嗯。我不能。我需要使用帖子。非常感謝你。 :) – Wilson