douao7937 2014-05-30 22:54
浏览 46

如何在Javascript中转义PHP变量?

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. Through PHP it echoes out fine but when I do it through Javscript, however, quotes seem to be unescaped (specifically single quotes). 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)

WHAT IT SHOULD BE:
Macy's Herald Square

Any help or guidance on why this is happening? Thx in advance...

  • 写回答

2条回答 默认 最新

  • duanbiaoshu2021 2014-05-30 23:17
    关注

    You can use html_entity_decode:

    I'm not really familiar with wordpress, but I suppose you would use it inside 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 = html_entity_decode(json_encode($array), ENT_COMPAT , "UTF-8");
    

    EDIT: added ENT_COMPAT , "UTF-8"

    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀