ajax作为JSON对象将数据发送和存储到rails

ajax作为JSON对象将数据发送和存储到rails

本文介绍了如何通过jquery/ajax作为JSON对象将数据发送和存储到rails?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{问题更新}

我想向安装了rails的服务器发送一些数据.我的数据采用JSON格式,例如:

I want to send some data to the server where rails is installed. My data is in JSON format such as:

var JSONObject=  {
             table1: {
                      title: "Title of text",
                      url: "Url of text"
                      }
                  }

并且我经常使用以下代码:

and I use the following code in cilent:

$.ajax({
            type: "POST",
            url : "http://webadress.com/table1",
            cache: false,
            data: JSONObject,
             statusCode: {

                 200:function() { alert("200"); },
                 202:function() { alert("202"); }
            },
            success: function() {  alert("Data Send!");},
            error: function(xhr){  alert("The error code is: "+xhr.statusText);}
        });

,并且在代码中,存在以下代码:

and in the cilent, the following code exists:

def create
    @table1= Table1.new(:title => params[:title], :url => params[:url])

respond_to do |format|
  if @table1.save
    format.html { redirect_to(@table1, :notice => 'User was successfully created.') }
    format.xml  { render :xml => @table1, :status => :created, :location => @table1}
    format.json { render :json => @table1}
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
    format.json  { render :json => @user.errors, :status => :unprocessable_entity }
  end
   end
end

但是它不起作用.如何获取数据并将其存储在数据库中.我是说如何将每个元素放入不同的列?

But it is not working.How can I get data and store it in a database. I mean how can I put each element into different columns?

推荐答案

最佳实践

Best practice

首先,您应该在else语句中响应json,因为如果无法保存Table1,您将获得不适当的406(不可接受)响应代码. 422(不可处理实体)合适.

First of all you should respond to json in the else statement, because if Table1 cannot be saved you are going to get a 406 (Not Acceptable) response code which is inappropriate. 422 (Unprocessable Entity) is appropriate.

format.json  { render :json => @user.errors, :status => :unprocessable_entity }

解决方案

Solution

然后我认为错误在于以下语句

Then I think the error is in the following statement

params[:table1]

1..如果按照您说的那样发送数据,则可以执行以下操作

1. If your data are being sent like you said, you can do something like this

@table1= Table1.new(:title => params[:title], :url => params[:url])

2..如果您要编写简洁的代码,则应以这种方式发送数据

2. And if you want to write clean code you should send data this way

table1: {
  title: "Title of text",
  url: "Url of text"
}

通过将数据包装在table1中,您将不需要进行任何更改.

By wrapping your data in table1 you won't need to change anything.

这篇关于如何通过jquery/ajax作为JSON对象将数据发送和存储到rails?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 06:33