javascript - 使用 jquery 将文本替换为变量的值
问题描述
我已经创建了一个函数来sms message
使用从 db获取ajax get call
,成功后我想将{order_id}
文本替换为 order-id 之类的454574
,并且可能还有一些变量,例如客户名称等。
我的尝试
$(document).delegate('.sms-template', 'click', function() {
var tempID = $(this).attr('id').replace('sms-template-','');
var oID = $(this).attr('data-id').replace('sms-template-','');
$.ajax({
url: 'index.php?route=sale/order/getSmsTemplate&token=<?php echo $token; ?>&template_id='+tempID,
type: 'get',
dataType: 'json',
success: function(json) {
$('textarea#input-order-comment-'+oID).append(json['message']);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
它工作正常并显示message
为textarea
Dear {customer_name}, Your Order : {order_id} is successfully placed and ready to process.
我想用我存储在 php 变量中的编号替换 {customer_name} 和 {order_id}。
PS:我对RegEx的了解不多。
解决方案
这里最简单的很可能是replace()
string.replace("old value","new value")
例如
var the_id = "454574"; // or where you get that from
var new_message = json['message'].replace("{order_id}",the_id);
$('textarea#input-order-comment-'+oID).append(new_message);
根据评论和问题编辑更新
要替换其他信息,可以做这样的事情
var the_id = "Order id", the_name = "Customer name";
var new_message = json['message'].replace("{order_id}",the_id).replace("{customer_name}", the_name);
$('textarea#input-order-comment-'+oID).append(new_message);
如果有更多的替代品,这里有一个有一些巧妙解决方案的帖子:
推荐阅读
- latex - 章节末尾的乳胶浮动数字,而不是页面
- lisp - Common LISP 中出现奇怪的“EVAL:未定义函数 T”错误
- spring - NoOpPasswordEncoder 不工作,返回状态码 200 而不是 401
- google-analytics - 测量协议事件跟踪和 analytics.js 或标签管理器事件跟踪有什么区别?
- amazon-web-services - 断开连接后保持 AWS EC2 Windows 服务器终端应用程序处于活动状态
- c# - 图像分类中 Ml.net 中的异常
- webpack - 即使我在 webpack 中定位它,也找不到带有本机扩展的 react-native-web 模块
- javascript - Vue分隔符不在属性中工作,但在元素中工作
- php - Nginx 没有正确加载 JS、CSS
- git - git 开关保留被忽略的文件夹