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

Ember应用中点击Select按钮获取并渲染RoomNo值的方案咨询

Ember表格点击Select按钮获取RoomNo并渲染的解决方案

问题说明

开发Ember应用从Servlet获取数据并以表格展示,需求是点击每行的Select按钮,将对应行的RoomNo值渲染到指定区域。当前遇到两个问题:

  1. Handlebars模板中按钮点击事件无法正确传递RoomNo参数
  2. 不清楚如何在Ember中引入jQuery(用于Ajax请求)

修复步骤

1. 修正Handlebars模板

原模板存在thead结构错误、按钮事件参数传递错误的问题,修改后的模板如下:

{{#if this.request.isPending}}
  loading data...
{{/if}}
<main class="conttainer mt-5">
  <div class="cond">
    <table border="1|0" class="tab">
      <thead>
        <tr>
          <th>Capacity</th>
          <th>Price</th>
          <th>RoomType</th>
          <th>RoomNo</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
        {{#each this.result as |row|}}    
          <tr>
            <td>{{row.Capacity}}</td>
            <td>{{row.Price}}</td>
            <td>{{row.RoomType}}</td>
            <td>{{row.RoomNo}}</td>
            <td>
              <button class="btn-test" {{on "click" (fn this.getroomno row.RoomNo)}}>
                Select
              </button>
            </td>
          </tr>
        {{/each}}
      </tbody>
    </table>
  </div>
  <form>
    <table>
      <tr>
        <td><h5>room number</h5></td>
      </tr>
      <tr><td>{{this.room}}</td></tr>
      <tr><td><b>Enter the Start Date</b></td></tr>
      <tr><td><input type="date" placeholder="yyyy-mm-dd" id="sdate" value="2022-07-01" min="2022-07-01" max="2022-07-31"></td></tr>
      <tr><td><b>Enter the End Date</b></td></tr>
      <tr><td><input type="date" placeholder="yyyy-mm-dd" id="edate" value="2022-07-01" min="2022-07-01" max="2022-07-31"></td></tr>
      <tr><td><button type="button" {{action "get"}}>submit</button></td></tr>
    </table>
  </form>
</main>

修改点:

  • 移除thead中th嵌套td的错误结构,直接在th中定义表头
  • 放弃each-in遍历所有字段,改为显式渲染每一列,避免重复显示RoomNo
  • 使用(fn this.getroomno row.RoomNo)传递RoomNo参数,这是Ember事件传递参数的标准写法

2. 优化控制器代码

简化事件处理逻辑,修正Ajax请求的上下文问题:

import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { service } from '@ember/service';
import { resource } from 'ember-resources';

class RequestState {
  @tracked value;
  @tracked error;

  get isPending() {
    return !this.error && !this.value;
  }
}

export default class RoomselectController extends Controller {
  @service router;
  @tracked room = 0;

  getroomno(value) {
    this.room = value;
    console.log('Selected RoomNo:', this.room);
  }

  @use request = resource(({ on }) => {
    const state = new RequestState();

    // 用箭头函数保留控制器上下文,无需额外变量
    $.ajax({
      url: 'http://localhost:8080/hotelres/My',
      method: 'GET',
      dataType: 'json',
      success: (response) => { 
        console.log(response);
        if (response == 0) {
          this.router.transitionTo('error');
        } else {
          state.value = response;
        }
      },
      error: (xhr, status, error) => {
        state.error = `${status}: ${xhr.statusText}`;
      },
    });

    return state;
  });

  get result() {
    return this.request.value || [];
  }
}

修改点:

  • getroomno方法直接使用this赋值,移除冗余的that变量
  • Ajax回调改用箭头函数,直接访问控制器的this,无需dis变量
  • 明确调用this.router.transitionTo实现路由跳转

3. Ember中引入jQuery的方法

Ember 3.24+版本不再默认包含jQuery,需手动安装:

  1. 安装依赖:
npm install ember-cli-jquery --save-dev
  1. 在ember-cli-build.js中添加配置:
'use strict';

const EmberApp = require('ember-cli/lib/broccoli/ember-app');

module.exports = function(defaults) {
  let app = new EmberApp(defaults, {
    jquery: {
      source: 'node_modules/jquery/dist/jquery.min.js',
      testSource: 'node_modules/jquery/dist/jquery.min.js'
    }
  });

  return app.toTree();
};

替代方案:使用原生fetch代替jQuery Ajax,无需引入额外依赖:

// 替换控制器中的Ajax部分
fetch('http://localhost:8080/hotelres/My', { method: 'GET' })
  .then(response => response.json())
  .then((response) => {
    console.log(response);
    if (response == 0) {
      this.router.transitionTo('error');
    } else {
      state.value = response;
    }
  })
  .catch((error) => {
    state.error = `Request failed: ${error.message}`;
  });

验证效果

完成上述修改后,点击每行的Select按钮,对应的RoomNo会自动赋值给this.room并渲染到表单指定区域,无需额外操作。

内容的提问来源于stack exchange,提问作者hariharan baskaran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 12:15:41