[英]Not sure how to parse this PHP/JSON object in Javascript/jQuery
So from what I understand, because I created a JSON object in PHP using json_encode
and then used echo
to display it, I can access it directly as an object in JS, like this 所以从我的理解,因为我使用
json_encode
在PHP中创建了一个JSON对象然后使用echo
来显示它,我可以直接将其作为JS中的对象访问,就像这样
.done(function(response) {
var result = response;
$(result).hide().prependTo('#messages').fadeIn('slow');
});`
However, how do I access the data within the object? 但是,如何访问对象内的数据? My object contains
error
which will be either true or false, and error_message
while contains the errors formatted as <li>error</li>
我的对象包含
error
,该error
将为true或false, error_message
包含格式为<li>error</li>
PHP returns this - {"error":true,"error_messages":" <li>Name too short (minimum of 4 characters)<\\/li> <li>Name too short (minimum of 4 characters)<\\/li>"}
PHP返回 -
{"error":true,"error_messages":" <li>Name too short (minimum of 4 characters)<\\/li> <li>Name too short (minimum of 4 characters)<\\/li>"}
If your server returns the correct Content-Type
header ( application/json
), jQuery will parse the response for you and give you an object, which you can use like this: 如果您的服务器返回正确的
Content-Type
标头( application/json
),jQuery将为您解析响应并为您提供一个对象,您可以像这样使用:
console.log(response.error_messages); // "<li>Name too short...
If your server does not return the correct Content-Type
header, you can force the issue by supplying 如果您的服务器未返回正确的
Content-Type
标头,则可以通过提供来强制解决问题
dataType: "json"
in your $.ajax
call. 在你的
$.ajax
电话中。
Either way, the JSON you've quoted in the comment on your question is valid. 无论哪种方式,您在问题评论中引用的JSON都是有效的。
So it may be that you want: 所以你可能想要:
if (response.error) {
$(response.error_messages).hide().prependTo('#messages').fadeIn('slow');
}
else {
// whatever you show when it's successful
}
But note that #messages
must be a menu
, ul
, or ol
element, since your error_message
defines an li
element . 但请注意,
#messages
必须是menu
, ul
或ol
元素,因为error_message
定义了li
元素 。
You should just be able to use it as an object like normal. 您应该能够像平常一样将它用作对象。 Eg:
例如:
result.error; // true or false
result.error_messages; // the error messages
You may need to parse it, but jQuery (which it looks like you're using) may do that for you. 您可能需要解析它,但jQuery(它看起来像您正在使用)可能会为您做到这一点。 If it doesn't, use
JSON.parse
: 如果没有,请使用
JSON.parse
:
var myobj = JSON.parse(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.