简体   繁体   English

Laravel刀片逃生jQuery

[英]Laravel blade escape jquery

In my laravel 4 project users can submit textarea data. 在我的laravel 4项目中,用户可以提交textarea数据。 I know I can escape user data with {{{ }}} in my views, But what should i do if i get the data with ajax ? 我知道我可以在视图中使用{{{}}}来转义用户数据,但是如果我使用ajax获取数据该怎么办? It is a jquery variable i cant escape it with the brackets. 这是一个jquery变量,我无法使用方括号将其转义。 For example if I handle response from ajax like : 例如,如果我处理来自ajax的响应,例如:

$.each(response, function( key, value ) 
{
    $('#div').append('<div>'+value.notEscapedData+'<div>')
});

And the controller where the data comes from is for example. 例如,数据来自的控制器。

$response = Data::all()
return $response;

You can either do it with javascript (and you will find plenty solutions on the internet. eg the link @Thrustmaster posted in the comments) or you can do it in Laravel. 您可以使用javascript(并且您会在Internet上找到很多解决方案,例如,评论中张贴的链接@Thrustmaster)中进行操作,也可以在Laravel中进行操作。

When you use Blades triple curly braces {{{ }}} it compiles to a call to e() (which then calls htmlentities ) 当您使用Blades三重花括号{{{ }}}它会编译为对e()调用(然后调用htmlentities

So you can use e('string-containing-html') to escape the string. 因此,您可以使用e('string-containing-html')来转义字符串。

You could use a model attribute accessor for the escaping but I suppose you will need the string unescaped sometimes so here are a two other options: 您可以使用模型属性访问器进行转义,但是我想您有时有时需要将字符串转义,所以这里有两个其他选择:

toArray() toArray()

Override the toArray() method in your model 覆盖模型中的toArray()方法

public function toArray(){
    $array = parent::toArray();
    $array['attribute_name'] = e($array['attribute_name']);
    return $array;
}

This way every time the model gets converted into an array (which is used for converting it into JSON=, the property will be escaped. 这样,每次将模型转换为数组(用于将其转换为JSON =时,该属性都会被转义)。

Loop over it in your controller 在控制器中循环播放

$data = Data::all();
$data->each(function($d){
    $d->attribute_name = e($d->attribute_name);
});
return Response::json($data);

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

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