将Php-array发送给JavaScript-variable.获取SyntaxError: Unexpected令牌


Sending Php-array to JavaScript-variable. Get a SyntaxError: Unexpected token :

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

我的JavaScript代码行,在php-document的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.
    }

您在这里执行echo

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

然后也做

json_encode(getProductTypes()) 

表示输出两次。因此出现了意外的标记错误。调用getProductTypes()函数将输出为字符串。

php函数错误。正如Murtaza Khursheed Hussain所解释的那样,我在返回语句之前在函数中使用echo会产生问题。删除那. .现在它起作用了!