将Php-array发送到JavaScript变量。获取SyntaxError:意外的令牌:

时间:2016-06-28 07:17:45

标签: javascript php json

我正在尝试将一个数组从php发送到我的Javascript变量中,但我得到一个Unexpected token :-error

我在JavaScript中的行,包含在php文档中的script-tag中:

arrayProductTypesFromDB = <?php echo json_encode(getProductTypes()); ?>;

我上面调用的php函数代码:

function getProductTypes(){
        //here I have code which fetches from database and makes $result into an stdClass-object. This works fine, as I can successfully use that object within php
        foreach ($result as $r) {
            echo 'id: ' . $r->id . ", type: " . $r->type_name . ", ins: " . $r->nbr_ins . "<br>"; //this works fine
        }

        $array = json_decode(json_encode($result), true); //this turns it into an array, and this works fine within php
        echo $array[0]['id']; //no problem here
        return $array; //this is what I send to JavaScript.. and it doesn't work.
    }

2 个答案:

答案 0 :(得分:0)

此错误在php函数内。正如Murtaza Khursheed Hussain解释的那样,在返回语句之前我在函数内使用echo引起了问题。删除了..现在它正在运行!

答案 1 :(得分:0)

你在这里回声

echo $array[0]['id']; 

然后也在做

json_encode(getProductTypes()) 

这意味着它输出两次。因此意外的令牌错误。调用getProductTypes()函数将输出到字符串。