php - magento escape string for javascript - Stack Overflow

Is there a helper function that will properly escape a string to be rendered as a single quote quoted J

Is there a helper function that will properly escape a string to be rendered as a single quote quoted JavaScript string literal?

I know of jsQuoteEscape but it only handles quotes and does not treat \n & \r etc.

so if my string is 'line1\nlineb' (i.e. two lines with a newline between them)

and I use

var jsvar='<?php echo $this->helper('myextension')->jsQuoteEscape($mystring); ?>';

I will get in the rendered content

    var jsvar='line1
line2';

which is a syntax error.

Thanks, Eyal

Is there a helper function that will properly escape a string to be rendered as a single quote quoted JavaScript string literal?

I know of jsQuoteEscape but it only handles quotes and does not treat \n & \r etc.

so if my string is 'line1\nlineb' (i.e. two lines with a newline between them)

and I use

var jsvar='<?php echo $this->helper('myextension')->jsQuoteEscape($mystring); ?>';

I will get in the rendered content

    var jsvar='line1
line2';

which is a syntax error.

Thanks, Eyal

Share Improve this question edited Jan 22, 2011 at 23:09 Alana Storm 166k95 gold badges419 silver badges622 bronze badges asked Jan 22, 2011 at 22:26 epelegepeleg 11k18 gold badges111 silver badges158 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Yes

$string = 'Hello
There';                     
var_dump( Mage::helper('core')->jsonEncode($string) );
var_dump( json_encode($string) );

I've never been clear if this encoding a non-object string datatypes as a javascript string is a side-effect of the JSON encoding, or if it's true, according to Hoyle Crockford JSON, so I always like to wrap my strings in an object when passing them around

$o = new stdClass();
$o->param = 'This is my 
Param';         
$json = json_encode($o);            
echo 'var data = ' . $json . ';' . "\n";
echo 'var jsdata = data.param';

This is how you'd handle this with javascript. There's no method that's build specifically for this. If you're interested in seeing the helper methods you do have available from a block, checkout the methods in

app/code/core/Mage/Core/Block/Abstract.php        
app/code/core/Mage/Core/Block/Template.php        

and if you're dealing with a template that's part of a block higher up the chain, get its class and then check its definition

var_dump get_class($this);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745120917a4612406.html

相关推荐

  • php - magento escape string for javascript - Stack Overflow

    Is there a helper function that will properly escape a string to be rendered as a single quote quoted J

    6小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信