简体   繁体   English

为什么这些对象属性未定义?

[英]Why are these Object Properties undefined?

I'm trying to access the properties of an object returned from my php script using json_encode like so: 我正在尝试使用json_encode访问从我的PHP脚本返回的对象的属性,如下所示:

php 的PHP

echo json_encode(array(
  'person_id' => $personID,
  'job_id' => $jobID)
);

JS JS

$.ajax({
  url: url,
  cache: false,
  type: "POST"
}).done(function(sData){
  console.log(sData);
  console.log(sData.job_id);
  console.log(sData.person_id);
});

Output: 输出:

{"person_id":1,"job_id":1}
undefined
undefined

What's going on here? 这里发生了什么? Why can't I access these properties? 为什么我不能访问这些属性?

UPDATE: 更新:

For any future visitors, this is a mistake I've made MANY, MANY times before (leaving out dataType ) and will most certainly make again. 对于任何未来的访问者来说,这是我之前犯过很多次错误了( dataType ),并且肯定会再次犯错。

It can be especially confusing because when you examine your server response in Chrome Dev Tools, it is automatically parsed as a JSON object (in the PREVIEW tab). 这可能特别令人困惑,因为当您在Chrome开发工具中检查服务器响应时,它会自动解析为JSON对象(在PREVIEW标签中)。

在此处输入图片说明

It's nice that Chrome does this, so that you can easily inspect your response data, however the same is not true for your javascript code, you WILL NEED to declare the proper dataType of the response so that your code can interpret the data as an object and not a string. Chrome可以很好地做到这一点,以便您可以轻松检查响应数据,但是对于JavaScript代码却并非如此,您需要声明响应的正确dataType ,以便您的代码可以将数据解释为对象而不是字符串。

$.ajax doesn't evaluate the response as JSON by default. $.ajax默认情况下不将响应评估为JSON。 you have to pass dataType: 'json' 你必须传递dataType: 'json'

This should do it 这应该做

$.ajax({
    url: url,
    cache: false,
    type: "POST",
    dataType: 'json'
}).done(function(sData){
        console.log(sData);
        console.log(sData.job_id);
        console.log(sData.person_id);
});

PHP returns a string value. PHP返回一个字符串值。 This value has to be parsed into a javascript object. 此值必须解析为javascript对象。 Try this: 尝试这个:

 $.ajax({
   url: url,
   cache: false,
   type: "POST"
 }).done(function(sData){
   sData = JSON.parse(sData);
   console.log(sData);
   console.log(sData.job_id);
   console.log(sData.person_id);
});

JSON is not an object/associative array but a string representation of one. JSON不是对象/关联数组,而是一个字符串表示形式。 JSON allows you to send object across languages but it must be parsed from the string into the value in that language. JSON允许您跨语言发送对象,但必须将其从字符串解析为该语言的值。 In jQuery you can just set the dataType but the important note is that in any language you have to parse the JSON. 在jQuery中,您可以只设置dataType但是重要的是,您必须以任何语言解析JSON。

sData - string sData字符串

use jQuery.parseJSON or jQuery.getJSON() 使用jQuery.parseJSONjQuery.getJSON()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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