簡體   English   中英

不知道如何在Javascript / jQuery中解析這個PHP / JSON對象

[英]Not sure how to parse this PHP/JSON object in Javascript/jQuery

所以從我的理解,因為我使用json_encode在PHP中創建了一個JSON對象然后使用echo來顯示它,我可以直接將其作為JS中的對象訪問,就像這樣

.done(function(response) {
    var result = response;
    $(result).hide().prependTo('#messages').fadeIn('slow');
});`

但是,如何訪問對象內的數據? 我的對象包含error ,該error將為true或false, error_message包含格式為<li>error</li>

PHP返回 - {"error":true,"error_messages":" <li>Name too short (minimum of 4 characters)<\\/li> <li>Name too short (minimum of 4 characters)<\\/li>"}

如果您的服務器返回正確的Content-Type標頭( application/json ),jQuery將為您解析響應並為您提供一個對象,您可以像這樣使用:

console.log(response.error_messages); // "<li>Name too short...

如果您的服務器未返回正確的Content-Type標頭,則可以通過提供來強制解決問題

dataType: "json"

在你的$.ajax電話中。

無論哪種方式,您在問題評論中引用的JSON都是有效的。

所以你可能想要:

if (response.error) {
    $(response.error_messages).hide().prependTo('#messages').fadeIn('slow');
}
else {
    // whatever you show when it's successful
}

但請注意, #messages 必須menuulol元素,因為error_message定義了li元素

您應該能夠像平常一樣將它用作對象。 例如:

result.error; // true or false
result.error_messages; // the error messages

您可能需要解析它,但jQuery(它看起來像您正在使用)可能會為您做到這一點。 如果沒有,請使用JSON.parse

var myobj = JSON.parse(result);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM