简体   繁体   English

jgent的magento转义字符串

[英]magento escape string for javascript

Is there a helper function that will properly escape a string to be rendered as a single quote quoted JavaScript string literal? 是否有一个帮助函数可以正确地转义字符串,以呈现为引用JavaScript字符串文字的单引号?

I know of jsQuoteEscape but it only handles quotes and does not treat \\n & \\r etc. 我知道jsQuoteEscape但它只处理引号而不处理\\ n&\\ r \\ n等。

so if my string is 'line1\\nlineb' (ie two lines with a newline between them) 所以如果我的字符串是'line1 \\ nlineb'(即两行之间有换行符)

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 谢谢,Eyal

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 根本不清楚,如果将非对象字符串数据类型编码为javascript字符串是JSON编码的副作用,或者它是真的,根据Hoyle Crockford JSON,所以我总是喜欢将我的字符串包装成一个传递它们时的物体

$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. 这就是你用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);

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

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