简体   繁体   English

使用jQuery将文本替换为变量的值

[英]replace text to variable's value using jquery

I have created a function to get sms message from db using ajax get call and after success i want to replace the {order_id} text to order-id like 454574 and may b few more variables like customer name etc. 我创建了一个函数,使用ajax get call从数据库获取sms message ,成功后,我想将{order_id}文本替换为order-id,例如454574并可能会添加一些变量,例如客户名称等。

MY TRY 我的尝试

$(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);
    }
  });
});

It works fine and display message in textarea as 它工作正常,并在textarea显示message

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

i want to replace {customer_name} & {order_id} with its number which i have stored in php variable. 我想用存储在php变量中的编号替换{customer_name}&{order_id}。

PS: I don't have much knowledge of RegEx. PS:我对RegEx并不了解。

The simplest here would most likely be a replace() 这里最简单的可能是replace()

string.replace("old value","new value")

Eg 例如

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);

Updated based on a comment and question edit 根据评论和问题进行了更新

To replace additional info, one could do something like this 要替换其他信息,可以执行以下操作

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);

If there will many more replacements, here is a post that have some clever solutions: 如果会有更多替代产品,那么此帖子提供了一些巧妙的解决方案:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM