【问题标题】:jQuery string concatenation not working with LaraveljQuery字符串连接不适用于Laravel
【发布时间】:2016-09-06 12:16:40
【问题描述】:

在我的代码中,我试图像这样连接我的 jQuery 变量

 user_username = $(this).parent().parent().children('td:nth-child(15)').text(); //value is m

但是这行得通

 $('#photo').attr('src', "{{ route('account.image', ['filename' => 'm.jpg']) }}"); // the image is showing

虽然没有

 $('#photo').attr('src', "{{ route('account.image', ['filename' => '"+user_username+".jpg']) }}"); // the image is not showing

注意:我正在使用 laravel 显示图像

问题是当我提醒我的字符串时,它返回 %22+user_username+%22.jpg 而不是 m.jpg

【问题讨论】:

  • “不工作”是什么意思?
  • user_username 有价值吗?
  • 是的,值为m
  • 检查 img src 是否已更改为您的值。
  • 再次:“不工作”是什么意思?价值是否丢失?语法错误?有什么事吗?

标签: jquery laravel variables concatenation


【解决方案1】:

你可以这样吗..

只需用这个替换你的 src 所在的行。

var path = "{{ route('account.image',['filename' => 'example']) }}";

$('#photo').attr('src', path.raplace('example', user_username+'.jpg'));

【讨论】:

    【解决方案2】:

    我对laravel不太了解,但是这一行是laravel特定的php模板标签:

    {{ route('account.image', ['filename' => '"+user_username+".jpg']) }}
    

    所以你的 javascript var 不是路由的一部分,因为它是由 PHP 在运行时生成的。

    我可能是错的,但没有其他可能是原因。所以你必须通过 laravel 设置文件名或者在路由标签之外设置文件名。

    编辑:尝试使用空文件名获取路由并将文件名连接到 laravel 标记后:

    $('#photo').attr('src', "{{ route('account.image', ['filename' => '']) }}"+user_username+".jpg");
    

    另一种解决方案(通过jQuery更改文件名):

    $('#photo').attr('src', "{{ route('account.image', ['filename' => '"+user_username+".jpg']) }}");
    
    var src = $('#photo').attr('src'); 
    var path = src.substring(0,src.lastIndexOf('/'));
    
    $('#photo').attr('src', path + '/' + user_username + '.jpg');
    

    【讨论】:

    • $('#photo').attr('src', "{{ route('account.image', ['filename' => '"+user_username+".jpg']) } }");我要改变我的img的src
    • 是的,但是 laravel 标签的 user_username 不存在。
    • 我使用 jquery 先生。当我提醒我的字符串返回 %22+user_username+%22.jpg 而不是 m.jpg 时,我发现了我的问题
    • 请理解,在 laravel 标签内,您是在 PHP 端。所以你的 javascript var user_username 是一个简单的字符串。这也解释了为什么它被解析为%22+user_username+%22.jpg
    • 嗯,先生,我能做什么?我应该将 jquery 转换为 php 吗?
    猜你喜欢
    • 2017-10-15
    • 2018-02-20
    • 1970-01-01
    • 2015-11-23
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多