简体   繁体   English

如何在Javascript中转义PHP变量?

[英]How To Escape a PHP Variable in Javascript?

I am trying to create a Javascript function that echoes out a Wordpress function called the_title() which just returns the title of the a blog. 我正在尝试创建一个Javascript函数,该函数回显一个名为the_title()的Wordpress函数,该函数仅返回博客的标题。 Through PHP it echoes out fine but when I do it through Javscript, however, quotes seem to be unescaped (specifically single quotes). 通过PHP,它回声很好,但是当我通过Javscript执行时,引号似乎是未转义的(特别是单引号)。 Any help or explanation why this is happening? 任何帮助或解释为什么会这样?

THE CODE: 编码:

function createSliderTabs() {   
    var para = document.createElement("li");
    var strings = "<?php the_title(); ?>";
    var post_string = strings.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");
    var node = document.createTextNode(post_string);
    para.appendChild(node);
    var element = document.getElementById("control-navigation");
    element.appendChild(para);
}

    createSliderTabs();

THE RESULT: 结果:
Macy&#8217 ;s Herald Square (had to include space or it would've changed to single quote) 梅西百货(Macy's Herald Square)(必须包含空格,否则它将变成单引号)

WHAT IT SHOULD BE: 应该是:
Macy's Herald Square 梅西百货先驱广场

Any help or guidance on why this is happening? 有什么帮助或指导,为什么会这样? Thx in advance... 提前谢谢...

From php to js transformation you always have to use json_encode() . 从php到js转换,您始终必须使用json_encode()

You can use html_entity_decode : 您可以使用html_entity_decode

I'm not really familiar with wordpress, but I suppose you would use it inside the_title(): 我对wordpress并不是很熟悉,但是我想您会在the_title()中使用它:

function the_title()
{
   $str = 'Macy&#8217;s Herald Square';
   echo html_entity_decode ($str, ENT_COMPAT , "UTF-8");
}

If you need to use json_encode() you should be able to do 如果您需要使用json_encode() ,则应该可以

$json = html_entity_decode(json_encode($array), ENT_COMPAT , "UTF-8");

EDIT: added ENT_COMPAT , "UTF-8" 编辑:添加了ENT_COMPAT , "UTF-8"

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

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