简体   繁体   English

如何将发布请求发送到 Rails 操作

[英]How to send post request to rails action

I'm new to rails so I don't know if that is the best practice.我是 Rails 的新手,所以我不知道这是否是最佳做法。 I'm trying to send user input from index view to the index action using ajax then update the view with user input.我正在尝试使用 ajax 将用户输入从索引视图发送到索引操作,然后使用用户输入更新视图。 I'm not trying to save this input in the database.我不是要将此输入保存在数据库中。

The @url always return nil. @url 总是返回 nil。

NOTE: I try to create a custom action with no luck because it requires a template.注意:我尝试创建一个没有运气的自定义操作,因为它需要一个模板。

Thanks in advance :)提前致谢 :)

The index action索引操作

def index
    @url = params[:option]
  end

The index view索引视图

<input type="text" id="exampleFormControlInput1">

<p id="resp-result"><%= @url %></p>


<script type="text/javascript">
        $(".button").click(function(event){
             var userinput = document.getElementById("form").value;
             console.log(userinput);
            event.preventDefault();
            $.ajax({
                url:"/responses/",
                type: "POST",
                data: {option: userinput},
                dataType: "text",
                success:function(result){
                  alert("success" + result);

                },
                error:function(result){
                   alert("error" + result);
                }
            });
        });
</script>

Yuna you will need to output response in json. Yuna 你需要在 json 中输出响应。 lets assume that your ajax script can send data to ruby on rails backend properly.让我们假设您的 ajax 脚本可以正确地将数据发送到 ruby​​ on rails 后端。

Try this尝试这个

at ajax not this在 ajax 不是这个

  url:"/responses/",

but

  url:"/responses.json",

you can then get result as per然后你可以得到结果

alert("success" + result.myurl);

you can myurl as part of the json response您可以将myurl作为 json 响应的一部分

Finally try this最后试试这个

def index
    respond_to do |format|
        #@url = params[:option]
        @url='nancy more url'
        format.json do
          render json: {myurl: @url}.to_json
        end
    end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM