Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/253.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何读取JSON返回的对象?_Php_Javascript_Ajax_Json_Jquery - Fatal编程技术网

Php 如何读取JSON返回的对象?

Php 如何读取JSON返回的对象?,php,javascript,ajax,json,jquery,Php,Javascript,Ajax,Json,Jquery,我正在尝试编写通知系统的代码。AJAX调用运行一个PHP脚本,该脚本选择每个“消息”,其中“new=1”。因此,我通过JSON_编码将PHP数组返回给JS 这将返回以下对象: 在我的原始页面上,您可以看到所有“会话”。我想用新消息的数量(=对象中记录的数量)来“更新”div(它有新消息)的文本 现在问题来了:我不知道如何读出那个物体。有人能帮我吗 非常感谢 如果您想要特定会话中的消息数,它应该是这样的: theObjectThatGotReturned[sessionName].length

我正在尝试编写通知系统的代码。AJAX调用运行一个PHP脚本,该脚本选择每个“消息”,其中“new=1”。因此,我通过JSON_编码将PHP数组返回给JS

这将返回以下对象:

在我的原始页面上,您可以看到所有“会话”。我想用新消息的数量(=对象中记录的数量)来“更新”div(它有新消息)的文本

现在问题来了:我不知道如何读出那个物体。有人能帮我吗


非常感谢

如果您想要特定会话中的消息数,它应该是这样的:

theObjectThatGotReturned[sessionName].length
// sessionName is the name of the session; in this case, "cgk" or "ur"
var newMessages = 0;
for(var i in theObjectThatGotReturned) {
   if ( /* here, you should test if i == a valid session name */) {
      newMessages += theObjectThatGotReturned[i].length;
   }
}
// newMessages is the number of new messages.

如果您想要所有会话中的消息数,则如下所示:

theObjectThatGotReturned[sessionName].length
// sessionName is the name of the session; in this case, "cgk" or "ur"
var newMessages = 0;
for(var i in theObjectThatGotReturned) {
   if ( /* here, you should test if i == a valid session name */) {
      newMessages += theObjectThatGotReturned[i].length;
   }
}
// newMessages is the number of new messages.

try:json=new函数(“return({“+ajax.responseText+”})”

我想要一个特定会话的消息数,但也需要每个会话的消息数。因此,在本例中,它将是:returnedObj[cgk].length和returnedObj[ur].length。问题是我不知道会话的“名称”(在本例中为UR&CGK),因此我必须循环它。我不完全确定您的意思。。。如果您不知道名称,您如何知道何时找到了正确的会话?…现在,如果您的意思是您事先不知道名称,但在运行时将其存储在变量中,那么。。。您可以使用我的第一个代码段。执行
object[sessionName]
操作时,浏览器将获取
sessionName
的值,并将其用作属性的名称。例如,如果
sessionName==“ur”
,那么
object[sessionName]==object[“ur”]==object.ur
。我很确定OP已经将它从字符串转换为对象。如果我没有弄错的话,他们问题中的图像实际上是Safari/Chrome调试器的屏幕截图,显示了对象的属性。