普通网友 2015-10-31 15:00
浏览 46

古怪的javascript php实现用php数据替换js中的数据回车中断javascript

I'm working on someone elses legacy code and they have a weird implementation where they do the following:

- load javascript file into php
- perform a string replace for variables, such as replacing `$intro` with mysql data in the javascript

My problem is that the $intro data contains carriage returns so when I perform the string replace into the javascript with the mysql data it causes the javascript to break.

Here is the line of code in javascript:

 dialog.i_intro.value="$intro";

And here is the line of code in php:

$ln=str_replace("\$intro",$intro,$ln);

And here is the data:

 dialog.i_intro.value = "Hello World
 Hello World
 Hello World";

How do I resolve this?

UPDATE I need the carriage returns in the javascript

Im trying the following:

In php:

$intro = str_replace("
","--carriage--",$intro);

In Javascript:

dialog.i_intro.value=dialog.i_intro.value.replace('--carriage--','
');

But something isn't working with this.

EXTENDED UPDATE

I've replaced all line breaks with html breaks. I discovered that the code is interpreting the js using eval. Here is my current javascript output of the intro variable.

dialog.i_intro.value="Hi Im Jonathan<br />
<br />
Hi Im Jonathan<br />
<br />
Hi Im Jonathan";

What should I do next?

  • 写回答

2条回答 默认 最新

  • dongsu4345 2015-10-31 15:20
    关注

    Javascript (at least currently deployed javascript in browsers, it should be easier in ES6) doesn't handle line endings in strings very intuitively. Your best bet is to escape the carriage returns, as in

     dialog.i_intro.value = "Hello World \
     Hello World \
     Hello World";
    

    That should not trigger an error and will preserve the line breaks you require.

    To implement, try this instead of your current PHP string replacement line:

    $intro = str_replace("
    "," \\
    ",$intro); 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?