【问题标题】:passing parameters to rails back end from an ajax call从 ajax 调用将参数传递给 rails 后端
【发布时间】:2015-12-18 21:38:23
【问题描述】:

我正在尝试将 API 路由传递给 rails,以便服务器而不是客户端执行调用。尝试执行此操作时找不到 404。当我将此路由传递给该方法时,它可以从控制台找到。但是不是来自 ajax 调用。这是我的控制器方法:

    def identification
       @link = params[:link]
       @response = MotorClient.new.response_from_path(@link)
       render json: @response
    end

这是我的路线:

    get '/identification/:link', to: 'vehicles#identification', on: :collection

这是我的 ajax:

    handleRoute: function (e) {
    this.handleChange(e);
    e.preventDefault();
    var options = e.target.options;
    var route = "";
    for (var i = 0, l = options.length; i < l; i++) {
        if (options[i].selected) {
            route = (options[i].dataset.route);
            console.log(route)
            $.ajax({
                type: 'get',
                url: '/vehicles/identification/',
                dataType: 'json',
                data: {"link":encodeURIComponent(route)},
                success: function (data) {
                    this.props.getMakes(data);
                }.bind(this),
            })
        }
    }
},

当我 console.log 路由时,我得到了正确的字符串,例如“/v1/Information/YMME/Years/2012/Makes/56/Models”,就像我从 rails 控制台说的那样,它可以工作,但我不能正确获取参数这是我通过 ajax 调用时在 javascript 控制台上得到的:

     GET http://localhost:3000/vehicles/identification/?link=%252Fv1%252FInformation%252FYMME%252FYears%252F2012%252FMakes 404 (Not Found)

我做错了什么?

【问题讨论】:

    标签: javascript ruby-on-rails ajax reactjs


    【解决方案1】:

    看起来您的路由期望 link 是 URL 路径中的一个段,而不是查询字符串变量:/identification/:link -- 尝试删除 /:link 或在 URL 末尾附加编码链接向服务器进行 AJAX 回调时。

    【讨论】:

      【解决方案2】:

      这里的关键是encodeURIComponent,它转义了链接字符串。最好以这种方式转义数据,所以我认为您最好在 API 端处理转义字符串格式。

      还有另一种方式:使用 'post' 而不是 'get' ajax 类型。因此,您可以删除转义部分并将纯字符串作为“链接”属性传递。

      【讨论】:

      • 如果您查看问题中的代码,链接已经通过encodeURIComponent 编码。
      猜你喜欢
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-09
      • 1970-01-01
      • 2012-11-18
      • 2010-12-27
      相关资源
      最近更新 更多