通过ajax调用将参数传递到rails后端

passing parameters to rails back end from an ajax call

本文关键字:rails 后端 参数传递 ajax 调用 通过      更新时间:2023-09-26

我正在尝试将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)

我做错了什么?

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

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

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