javascript - 如何在响应 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>'
);
这是我到目前为止尝试过的代码。但它没有显示变量内部的值。
解决方案
这是使用 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 调用之前)。我以前遇到过这个问题,根据用例的复杂程度,我用两种方式解决了它,这取决于你选择哪一种:
- 将 JS 用于 ajax 回调中的所有内容,并使用从 response:
first_name
、last_name
等接收到的变量。如果您有复杂的逻辑或在前端使用大量 PHP,这可能会变得非常乏味。 - 在服务器端生成 HTML 元素并将整个 html 作为字符串发送回。
// server side
return response()->json(['element' => $elementString]);
// client side
$('.profile_comment').prepend(res.element);
推荐阅读
- typo3 - TYPO3 TCA 默认文本多行/文本区域
- java - 从 Java 访问 Pervasive/Btrieve DB(DDF + DAT 文件)
- sql-server - SSRS 报告中定义的表达式显示#ERROR
- windows - 如何为文件操作设置 Echo 开/关
- tensorflow - 有没有办法设置 per_process_gpu_memory_fraction tensorflow.js (.JS!)?
- python - 无法将字符串转换为浮点数 - 将 Pandas 和 Numpy 用于 SVM 分类器
- python - 如何快速从 Klepto 文件存档中删除多个项目?
- java - 将 Elasticsearch json 请求拆分为每个 10MB 大小的块
- javascript - 如何检查是否有任何角色未分配给任何用户?
- javascript - 清除间隔不适用于javascript计时器