简体   繁体   English

不知道如何在Javascript / jQuery中解析这个PHP / JSON对象

[英]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 必须menuulol元素,因为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM