Re: How to convert this PHP into JavaScript [message #173176 is a reply to message #173173] |
Sat, 26 March 2011 06:03 |
Curtis Dyer
Messages: 34 Registered: January 2011
Karma:
|
Member |
|
|
sheldonlg <sheldonlg(at)thevillages(dot)net> wrote:
> On 3/25/2011 5:01 PM, Jerry Stuckle wrote:
>> On 3/25/2011 4:51 PM, Denis McMahon wrote:
>>> On Fri, 25 Mar 2011 15:22:42 -0400, Jerry Stuckle wrote:
>>>
>>>> On 3/25/2011 2:59 PM, sheldonlg wrote:
>>>> > On 3/24/2011 12:50 PM, Jerry Stuckle wrote:
>>>> >> On 3/24/2011 10:23 AM, Oltmans wrote:
>>>> >>> Hi PHP gurus, I hope you're doing well.
>>>> >>>
>>>> >>> I'm trying to convert a PHP script into JavaScript. I'm
>>>> >>> posting here because I don't know much PHP and I hope
>>>> >>> someone among you can help. Here is the PHP
<snip>
>>>> >> If you want to write javascript, you should ask in a
>>>> >> javascript newsgroup.
>>>> >>
>>>> > No Jerry, not this time. He has a PHP array and he wants to
>>>> > use that PHP array to generate a script in javascript. That
>>>> > means that knowledge of BOTH is required.
This is one of those cases in which I feel that cross-posting is
viable. The problem here is that the OP needs advice on how to
generate *quality* target code from PHP. Therefore, quality
JavaScript advice form people who are aware of subtle issues like
automatic semi-colon insertion (ASI), ECMAScript string literal
syntax, etc. are necessary.
<snip>
> I just, two days ago, had a need to do just that. What I did
> was:
I would consider outputting the below outside of PHP tags or
perhaps using heredoc syntax.
> print "<script>\n";
> print " var foo = new Array();\n";
Less verbose would be:
var foo = [];
> print " foo[0] = " . $foo[0] . ";\n";
You give no evidence here that `$foo[0]' is properly escaped to be
included in a string literal. There are important differences
between PHP's and JavaScript's one needs to keep in mind. In
addition to properly escaping quotes and backslashes, one needs to
take care that the JavaScript string literal has no actual line
terminators hard coded into it:
/* Invalid JavaScript string literal */
var foo = "bar
baz";
If I haven't missed anything, one way to escape the output for
JavaScript in PHP might look like:
$escaped = addcslashes($foo[0], "\"\n\r\\'");
<snip>
--
Curtis Dyer
<?$x='<?$x=%c%s%c;printf($x,39,$x,39);?>';printf($x,39,$x,39);?>
|
|
|