You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JSRender中替换数据?替换API返回数据launchUrl中的playerName

解决方案:替换API返回数据中的launchUrl字段值

看起来你已经成功拿到了API返回的游戏数据,现在需要批量替换每个游戏launchUrl里的playerName占位符对吧?我帮你调整了代码,核心思路是在渲染模板前遍历游戏列表,修改对应的URL字段:

$.ajax({
  type: "POST",
  url: "{{ $luckyStreakLobbyAPI }}",
  dataType: 'json',
  data: {
    Data: {
      Open: true,
      GameTypes: [],
      Currencies: []
    }
  },
  headers: {
    "Authorization": "Bearer " + "ey" // 这里建议把token存到变量里,不要硬编码哦
  },
  success: function (response) { // 把参数名改成response,避免和内部变量冲突
    $.views.settings.delimiters("<%", "%>");
    
    // 1. 提取游戏列表,避免覆盖原始响应数据
    let games = response.data.games;
    
    // 2. 替换launchUrl中的playerName(这里假设占位符是{playerName},根据实际格式调整)
    const currentPlayerName = "你的玩家名称"; // 替换成实际的玩家名称来源(比如登录用户的名字)
    games.forEach(game => {
      // 检查launchUrl是否存在,防止报错
      if (game.launchUrl) {
        game.launchUrl = game.launchUrl.replace("{playerName}", currentPlayerName);
      }
    });
    
    // 3. 渲染模板(补全你没写完的部分)
    var tmpl = $.templates('#luckyStreakTables');
    var html = tmpl.render(games);
    // 记得把渲染后的HTML插入到页面中,比如:
    // $('#targetContainer').html(html);
  },
  error: function(xhr, status, error) {
    // 别忘了添加错误处理,方便排查问题
    console.error("请求失败:", error);
  }
});

几个关键注意点:

  • 变量名冲突:把原代码中success的参数从data改成response,避免和内部的游戏列表变量重名导致数据覆盖。
  • 占位符匹配:如果你的launchUrl里的playerName是其他格式(比如{{playerName}}或者[playerName]),要对应修改replace方法里的第一个参数。
  • 容错处理:加了if (game.launchUrl)判断,防止某些游戏没有该字段时抛出错误。
  • 玩家名称来源:把currentPlayerName替换成实际的玩家名称获取方式,比如从登录态的全局变量、Cookie或者后端渲染的变量中获取。

内容的提问来源于stack exchange,提问作者Nicholas Déziel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:12:40