首页 > 解决方案 > 如何在响应 html 代码中显示 javascript 变量值?

问题描述

我希望用户在不重新加载页面的情况下发表评论。为此,我通过 jquery 应用了 ajax。当响应到来时,我已将 html 代码附加到刀片中。

 success: function(res)
            {
                
                var first_name = res.first_name;
                var last_name = res.last_name;
                var profilepic = res.profilepic;
                var created_at = res.created_at;
                $('.profile_comment').prepend(
                        '<div class="others_comment d-flex mb-15">'+
                            '<div class="users-img">'+
                                '<img @if(!empty('+profilepic+')) src="{{URL::asset("uploads/memberprofile/" . '+profilepic+')}}" @else src="{{URL::asset("member/assets/images/user.png")}}" @endif alt="user" class="img-fluid">'+
                            '</div>'+
                            '<div class="user_side">'+
                                '<div class="d-flex">'+
                                    '<h6 class="name">{{ucfirst('+first_name+')}} {{ucfirst('+last_name+')}}</h6>'+
                                    '@php $date= date("F d,Y", strtotime('+created_at+'));  @endphp'+
                                    '<p class="ml-auto font-xs">{{$date}}</p>'+
                                '</div>'+
                                '<p class="comment">{{ucfirst('+comment+')}}</p>'+
                                '<div  class="footer_comment d-flex">'+
                                    '<button class="btn-none ml-auto"> <img src="{{URL::asset("member/assets/images/option.svg")}}" alt="option" class="img-fluid"> </button>'+
                                '</div>'+
                            '</div>'+
                        '</div>'
                );

这是我到目前为止尝试过的代码。但它没有显示变量内部的值。

标签: javascriptjquerylaravel

解决方案


这是使用 Blade 和 JavaScript 时的经典问题。Blade 的工作方式是它会查看您的模板,然后将其编译成.php浏览器可以解释的适当文件。

这里发生的是,在执行任何脚本之前,刀片将运行其所有指令。例如,下面的行:

'<img @if(!empty('+profilepic+')) src="{{URL::asset("uploads/memberprofile/" . '+profilepic+')}}" @else src="{{URL::asset("member/assets/images/user.png")}}" @endif alt="user" class="img-fluid">'

会变成类似的东西

'<img src="localhost/storage/uploads/memberprofile/+profilepic+" alt="user" class="img-fluid">'

在执行任何脚本之前(所以在 ajax 调用之前)。我以前遇到过这个问题,根据用例的复杂程度,我用两种方式解决了它,这取决于你选择哪一种:

  1. 将 JS 用于 ajax 回调中的所有内容,并使用从 response: first_namelast_name等接收到的变量。如果您有复杂的逻辑或在前端使用大量 PHP,这可能会变得非常乏味。
  2. 在服务器端生成 HTML 元素并将整个 html 作为字符串发送回。
// server side
return response()->json(['element' => $elementString]);

// client side
$('.profile_comment').prepend(res.element);

推荐阅读