简体   繁体   English

PHP json_encode到JS对象不可用

[英]PHP json_encode to JS object not usable

I have an some PHP that looks like this: 我有一些看起来像这样的PHP:

$exec[0] = shell_exec("cat /etc/msm.conf | grep JAR_PATH");

$exec[1] = shell_exec("msm server list");
    if(strstr($exec[1],'[ ACTIVE ] "mc-srv" is running. Everything is OK.') !== FALSE){
        $exec[1] = 'mc online';
    }else{
        $exec[1] = 'mc offline';
    }

$exec[2] = shell_exec("sudo ts status");
    if($exec[2] == 'Server is running'){
        $exec[2] = 'ts online';
    }else{
        $exec[2] = 'ts ofline';
    }
echo json_encode($exec,JSON_FORCE_OBJECT);

An AJAX request gets sent to the page and the json is returned. AJAX请求被发送到页面,并返回json。 If I use console.log(JSON.parse(data)) I see this in the console Object {0: "DEFAULT_JAR_PATH="server.jar"↵", 1: "mc online", 2: "ts ofline"} however I can not access any of its methods even if i use an associative array. 如果我使用console.log(JSON.parse(data))我会在控制台Object {0: "DEFAULT_JAR_PATH="server.jar"↵", 1: "mc online", 2: "ts ofline"}Object {0: "DEFAULT_JAR_PATH="server.jar"↵", 1: "mc online", 2: "ts ofline"}即使使用关联数组,也无法访问其任何方法。

but If i create a new object and print that to the console it (in chrome atleast) looks exactly the same in terms of syntax highlighting exect I can access it via obj.method. 但是,如果我创建一个新对象并将其打印到控制台,则在语法高亮显示exect方面,它(在chrome atleast中)看起来完全相同,我可以通过obj.method访问它。

What am I doing wrong here? 我在这里做错了什么?

Based on how the object is being output in the console, it looks like it's being parsed okay by JSON.parse and is valid. 根据对象在控制台中的输出方式,看起来好像已被JSON.parse解析为正确且有效。

In which case, you should be able to access each method like this: 在这种情况下,您应该能够像这样访问每个方法:

var obj = JSON.parse(data);
console.log( obj['0'] ); // returns "DEFAULT_JAR_PATH="server.jar""
console.log( obj['1'] ); // returns "mc online"

obj.0 won't work in this case because the method names are numbers. obj.0在这种情况下不起作用,因为方法名称是数字。

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

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