简体   繁体   中英

Sending request to the controller via ajax removing slashes from namespace?

onclick="loadInlineEditor({
                        class:'<?= get_class($content) ?>', 
                        model_id:<?= $content->id ?>,
                        attribute:'description'
                    })"

Output for get_class($content) should be app\models\Page

But Inside controller this appmodelsPage is how I get it back via sending it as AJAX request

AJAX code:-

function loadInlineEditor(data) {
        $.ajax({
                url: '<?= Url::toRoute(["//url"]) ?>',
                type: 'POST',
                data: data,
                dataType: 'json'
            })

Output Code:-

Array
(
    [class] => appmodelsPage
    [model_id] => 1
    [attribute] => description
)

It's not ajax that is removing the slashes. It's because the js code generated by php looks like this:

loadInlineEditor({
    class:'app\models\Page', 
    model_id: 1,
    attribute:'description'
})

But \ (backslash) character in JS string is used as escape char. If you want to use backslash in JS string you have to escape it by itself as \\ .

To do that you can use either addslashes() php function or json_encode() .

onclick="loadInlineEditor({
    class:'<?= addslashes(get_class($content)) ?>', 
    model_id:<?= $content->id ?>,
    attribute:'description'
})"

The json_encode will add the " around the string so you don't have to use quotes too.

onclick="loadInlineEditor({
    class:<?= json_encode(get_class($content)) ?>, 
    model_id:<?= $content->id ?>,
    attribute:'description'
})"

Because the **** was an escape characters so you need to escape it before store him in the class properties.

So your code become:

onclick="loadInlineEditor({
                        class:'<?= addslashes(get_class($content)) ?>', 
                        model_id:<?= $content->id ?>,
                        attribute:'description'
                    })"

In fact the addslashes send app\models\Page to the class properties and it save to app\models\Page

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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