开发者

Sending JSON object in Rails via Post

This is a pretty straightforward question and I'm trying to bridge the gaps in my knowledge.

Quite simply the applications work as follows: 1: i: web app creates a hash of values 1: ii: Turns this hash into JSON 1: iii: Sends the JSON across to another application via POST THIS IS THE MAIN QUESTION

2: i: other web app receives the JSON, deserializes and turns back into an object.

@hostURL = 'http://127.0.0.1:20000/sendJson'

For 1 I've got i and ii done. Not too difficult.

@myHash = HASH开发者_StackOverflow中文版.new
    @myHash =
    {
      "myString" => 'testestestes'
      "myInteger" => 20
    }

    @myJsonHash = @myHas.to_json

Sending a post request in my application looks like this:

  res = Net::HTTP.post_form(URI.parse(@hostURL),
    {'myString'=>'testestestest, 'myInteger' => 20})

However I'm at a loss as to how to send the JSON hash across through post.

As for 2:

  @request = UserRequest.new({:myString => params[:myString], :myInteger => params[:myInteger] })
           if @request.save
    #ok
      puts "OBJECT CREATED AND SAVED"
    else
    #error
      puts "SOMETHING WENT WRONG WITH OBJECT CREATION"

Would this suffice as I hear Rails automatically deserializes on receiving a request.


On a side note: What should the response be?

These are 2 web apps communicating so returning some html would be bad. Possibly a numeric response? 200? 404?

Are there any industry standards when it comes to responding with data rather than responding to a browser


You want to use from_json which does the opposite of to_json. This will take the object being sent in JSON and convert it into ruby so your model or however you save it will understand.

@post = Post.new
@post.name = "Hello"

#this converts the object to JSON
@post.to_json 

@post = You want to use `from_json` which does the opposite of `to_json`. This will take the object being sent in JSON and convert it into ruby so your model or however you save it will understand.


@post = Post.new
@post.name = "Hello"

#this converts the object to JSON
@post.to_json 

@post = {
     "name" => 'Hello'
   }   

#this puts it back into JSON
@post.from_json

@post.name = "Hello"
@post.to_json

In terms of sending JSON (server side) to a controller that is usually done from JavaScript or AS3.

You should explain how you are posting. From a form, from a link. That matters; however, the easiest way is to use jQuery.

$.ajax({
    type: 'POST',
    url: url,
    data: data,
    success: success,
    dataType: json
});

Here you want the url to be the post url such has app.com/posts (your domain, and then a controller) and then the data should be in JSON format, for example:

data = {
         "name" => 'Hello'
       }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜