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

Rails实现无刷新页面更新用户值的技术问询

实现无刷新保存display值的API调用方案

1. 前端调整(阻止页面刷新,异步发送请求)

先修改表单代码,给表单添加唯一ID方便JS定位,移除按钮多余的href属性:

<div class="parent">
   <%= form_for(:display , url: '/fields/display', method: :put, id: 'display-form') do |f| %>
     <select name="display[display]" id="display_display">
     <option hidden><%= data['display']%></option>
     <option value="false">false</option>
     <option value="true">true</option></select>
     <%= f.hidden_field :id, value: field_id %>                   
     <button type="submit" class="round-6">✔</button>
   <% end %>
</div>

添加原生JavaScript代码,拦截表单默认提交行为,通过AJAX发送请求:

document.getElementById('display-form').addEventListener('submit', function(e) {
  // 阻止页面刷新的默认提交行为
  e.preventDefault();
  
  // 收集表单数据与请求信息
  const formData = new FormData(this);
  const requestUrl = this.action;
  const requestMethod = this.method;

  // 发送异步请求
  fetch(requestUrl, {
    method: requestMethod,
    headers: {
      // 携带Rails的CSRF令牌,避免请求被拦截
      'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content,
    },
    body: formData
  })
  .then(response => {
    if (response.ok) {
      // 保存成功后的自定义逻辑,比如提示用户或更新页面显示
      console.log('保存成功');
      const selectedValue = document.getElementById('display_display').value;
      document.querySelector('#display_display option[hidden]').textContent = selectedValue;
    } else {
      console.error('保存失败');
    }
  })
  .catch(error => {
    console.error('请求出错:', error);
  });
});

2. 后端控制器调整(返回JSON响应)

原控制器方法未明确返回响应,Rails会默认尝试渲染同名视图,需修改为返回JSON格式结果,方便前端判断操作状态:

def display
  @field = Api::AnalyticsQueryBuilderMetadataService::Field.update_field_display(params.require(:display).permit(:display,:id))
  
  # 根据操作结果返回对应JSON响应
  if @field.present?
    render json: { status: 'success', data: @field }, status: :ok
  else
    render json: { status: 'error', message: '保存失败' }, status: :unprocessable_entity
  end
end

3. 可选优化:发送JSON格式请求体

如果后端更适配JSON格式的请求数据,可修改JS中的请求部分:

// 手动收集并格式化数据
const requestData = {
  display: {
    display: document.getElementById('display_display').value,
    id: document.querySelector('[name="display[id]"]').value
  }
};

fetch(requestUrl, {
  method: requestMethod,
  headers: {
    'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content,
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(requestData)
})
// 后续成功/失败处理逻辑同上

完成以上修改后,点击保存按钮即可实现无刷新的API调用,完成display值的保存操作。

内容的提问来源于stack exchange,提问作者Animesh Arya

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:21:30