【问题标题】:passing data json in rails coffeescript and ajax在 rails coffeescript 和 ajax 中传递数据 json
【发布时间】:2014-12-01 07:21:01
【问题描述】:

我尝试了不同的方法来检索 json-data 失败

我的订单.js.coffee

 $.ajax(
  url: "/orders/", // want "/orders/1"  
  dataType: "JSON"    
 ).done (data) ->
   console.log data.status

我的控制器:

class OrdersController < ApplicationController
respond_to :json, :js, :html


def show
  @order = Order.find(params[:id])
  respond_with @order
end
....

我的 show.json.jbuilder

json.extract! @order, :id, :status

这里是我的路线:

get '/orders/:id', to: 'orders#show', defaults: {format: :json}
resources :orders, only: [:new, :create]
...

我用不同的方法遇到了很多错误。

Started GET "/orders/" for 127.0.0.1 at 2014-10-07 01:07:36 +0200

ActionController::RoutingError (No route matches [GET] "/orders"):

ERROR bad URI `/orders/%3C%=%20order.id%20%%3E'

【问题讨论】:

  • 您希望从 CoffeeScript 中的何处获取您的 id?你的order.js.coffee 应该是order.js.coffee.erb 吗?
  • 你为什么期望 1) 能够在你的咖啡脚本中评估 erb,它是在控制器上下文之外加载的,2) 期望向索引操作发出 get 请求会当您明确将订单操作限制为控制器中的 newcreate 操作时,您会做什么?
  • @JedSchneider 是我的错,我想获得对索引显示操作的请求,但我不知道如何:( 我想要一个类似的请求:url: "/orders/1 其中 1 是一个参数我想从表演动作中通过
  • $.get('/orders/1')
  • @JedSchneider 我没有很好地解释自己。示例:url: "/orders/11 是在每个新订单时更改的参数。换句话说,我需要这样的东西:/orders/:id,感谢您的宝贵时间。

标签: jquery ruby-on-rails-4 coffeescript


【解决方案1】:

我找到了一种解决方案,也许不是更好的解决方案,但它确实有效......

按顺序.js.coffee

id = $('#status_id').attr('data-id')
$.ajax
url: "/orders/#{id}"
type: "GET"
success: (data) ->    
  console.log(data)

在局部:

<div id="status_id" data-id="<%= @order.id %>">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    相关资源
    最近更新 更多