如何在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
相关产品推荐
相关产品推荐

