开发者

Call JavaScript Function from Symfony Component

开发者 https://www.devze.com 2023-02-06 07:07 出处:网络
I have created a new JSON string (by converting a PHP array using json_encode) and stored it in $siteTree ... outputting it to the log shows the following

I have created a new JSON string (by converting a PHP array using json_encode) and stored it in $siteTree ... outputting it to the log shows the following

[
{
    "attr": {
        "id": "node_1",
        "rel": "folder"
    },
    "data": "New Title",
    "children": [
        {
            "attr": {
                "id": "node_2",
                "rel": "folder"
            },
            "data": "second do开发者_JS百科cument",
            "children": []
        }
    ]
}

]

So I know the JSON is formed correctly. What I am trying to do is use that variable in a javascript function to create an object using the JSON data ... I am doing the following in the template

<?php
    use_helper('JavascriptBase');
    echo javascript_tag('createTree('.$siteTree.')');
?>

The following is shown on the output page

createTree([{&quot;attr&quot;:{&quot;id&quot;:&quot;node_1&quot;,&quot;rel&quot;:&quot;folder&quot;},&quot;data&quot;:&quot;New Title&quot;,&quot;children&quot;:[{&quot;attr&quot;:{&quot;id&quot;:&quot;node_2&quot;,&quot;rel&quot;:&quot;folder&quot;},&quot;data&quot;:&quot;second document&quot;,&quot;children&quot;:[]}]}]) 

The function is called but the JSON has replaced the " with &quote;. How can I stop this ?

Thanks for your help !


Symfony automatically performs output escaping to help prevent several types of XSS attacks.

You can disable it by configuration, or depending on what version of the Symfony framework you're using, access the raw data in your view like this:

$sf_data->getRaw('siteTree')

e.g.

echo javascript_tag('createTree(' . $sf_data->getRaw('siteTree') . ')');

If that doesn't work for you, you should find the relevant references you need by consulting the Symfony documentation for your version of the framework, searching for "output escaping".


OK .. So I managed to fix the problem ... this is how I did it ...I forgot about the json_encode and just passed an array up to the template of the component.

Within the template i processed it like this

echo javascript_tag('createTree('.json_encode($siteTree->getRawValue()).');');

This then output the correct JavaScript.

Thanks for everyones assistance ! Got there in the end

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号