[英]JSON/JQUERY/JS - Access properties from object
From my PHP processing file I receive back an object
( [object Object]
) and I'd like to access it's content's with calls like data[0].errors
etc, but all tries seem to fail for me. 从我的PHP处理文件中,我收到一个object
( [object Object]
),并且我想通过data[0].errors
等调用来访问它的内容,但是所有尝试似乎都对我失败了。
How may I achieve that? 我该如何实现?
Here's what the object looks like: 对象的外观如下:
" Array
(
[success] =>
[errors] => Array
(
[companyname] => Company name is required and must have 50 characters at most.
[logo1] => Logo is required.
[investment] => First investment amount is required.
[investment1] => Investment value must be an integer.
[payment] => Basic wage is required.
[payment1] => Payment value must be an integer.
[companytype] => Company type is required.
[companytype2] => Something is wrong with your company type.
)
)
"
I have to display those errors
in console div to show the user what has he done wrong. 我必须在控制台div中显示这些errors
,以向用户显示他做错了什么。
EDIT: 编辑:
Here's exactly what I get when I console.log(data)
: 这就是我console.log(data)
时得到的:
Also here's my AJAX request to make everything clear. 这也是我的AJAX请求,以使一切变得清晰。
$.ajax({
type : 'POST',
url : 'processcreatecompany.php',
data : formData,
dataType : 'json',
contentType: false,
processData: false,
encode : true
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
})
as expected the problem is in the php part ... you are doing a print_r
of the objects which gives that output that it's not json 如预期的那样,问题出在php部分...您正在执行对象的print_r
,该对象给出的输出不是json
you should use json_encode
to return the $data
object/array, so instead of 您应该使用json_encode
返回$data
对象/数组,所以不要
print_r($data['success']);
print_r($data['errors']);
you should have (also you should add the content type header ) 您应该拥有(还应该添加内容类型标头)
header('Content-Type: application/json');
echo json_encode($data);
Later edit: without the header you usually get the response as text/plain
in data.responseText
, as in your screenshot, and and you will have to do the JSON parsing "by hand". 以后的编辑:如果没有标题,通常会在data.responseText
以text/plain
形式获得响应,就像在屏幕截图中一样,并且您将不得不“手工”进行JSON解析。 Adding the header makes jQuery do the parsing automatically and you'll have the response as an object in data.response<something I dont recall now>
添加标头使jQuery自动执行解析,并且您会将响应作为data.response<something I dont recall now>
的对象。 data.response<something I dont recall now>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.