#alert "item was clicked-6ren">
gpt4 book ai didi

javascript - Rails4 - 对项目 Controller 的 AJAX 请求

转载 作者:行者123 更新时间:2023-11-30 17:27:10 25 4
gpt4 key购买 nike

$(document).ready ->
#... other code ...
$("#item-select2").click ->
#alert "item was clicked!" #this code works

在点击调用中,我试图将 AJAX 请求发送到带有所选项目 ID 的项目 Controller (方法“显示”)。在 controller#show 中,我想找到我们的项目并将其作为 json 返回。

我有一个表单,当在下拉列表中选择特定项目时,我想显示该项目的价格,因此我需要通过 AJAX 检索它,但我不确定如何检索。如果有人可以指导我,那将不胜感激。

我正在使用 Jbuilder

Continuation question

最佳答案

因为你有一个下拉列表,你需要监听更改事件,执行 Ajax 调用并将价格放入你想要的元素中,例如:

$(document).ready ->
$("#item-select2").change ->
selectedItem = $(this)
$.ajax([
"/items"
"/"
selectedItem.val()
".json"
].join("")).done (item) ->
$(".price").html item.price

在 Rails 端,您需要指定您的 Controller 响应 JSON通过在 Controller 顶部添加 respond_to :json,在操作线之前的下方,例如

class ItemsController < ApplicationController
before_action :set_item, only: [:show, :edit, :update, :destroy]
respond_to :json, :html

同时在您的 show 操作中更新您的响应,因此您同时支持 html 和 json,以防您没有使用某些 json 序列化程序(例如 jbuilder),如果您这样做,则不需要添加这些更改:

def show
respond_to do |format|
format.html
format.json { render json: @item.to_json }
end
end

希望对你有帮助,

干杯

关于javascript - Rails4 - 对项目 Controller 的 AJAX 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24005098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com