首页 > 解决方案 > 使用 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);
    }
  });
});

它工作正常并显示messagetextarea

Dear {customer_name}, Your Order : {order_id} is successfully placed and ready to process. 

我想用我存储在 php 变量中的编号替换 {customer_name} 和 {order_id}。

PS:我对RegEx的了解不多。

标签: javascriptphpjqueryregex

解决方案


这里最简单的很可能是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);

如果有更多的替代品,这里有一个有一些巧妙解决方案的帖子:


推荐阅读