简体   繁体   中英

how to pass data in json format to do an ajax post call in ruby?

First of all, I am calling a javascript ajax function that will call to the ruby function that gets called when I go to the URL:

/cnet

From there, I want to do another post call from ruby in which I want to pass json data. How do I pass json formatted data to do this call in ruby?

My javascript code is the following:

$.ajax({
  url: "/cnet",
  type: "get",
  dataType: "json",
  contentType: "application/json",
  data: {netname:netname},
  success: function(data) {
    alert(data);
  }
});

My ruby code is the following: Actually, I tried it in two different ways:

1.

get '/cnet' do  
  net_name=params[:netname]

  @toSend = {
    "net_name" => net_name
  }.to_json

  uri = URI.parse("http://192.168.1.9:8080/v2.0/networks")
  https = Net::HTTP.new(uri.host,uri.port)
  #https.use_ssl = true
  req = Net::HTTP::Post.new(uri.path, initheader = {'Content-Type' =>'application/json'})
  req['net_name'] = net_name
  req.body = "#{@toSend} "
  res = https.request(req)
  erb net_name
end

2.

get '/cnet' do  
  temp="mynet"
  url = URI.parse('http://192.168.1.9:8080/v2.0/networks') 
  params={'net_name'=>temp}
  resp = Net::HTTP.post_form(url, params)
  resp_text = resp.body
  print "======================================================================"
  puts resp_text    
  print "======================================================================"
  erb resp_text
end

How do I pass json data instead of a string?

Any help would be much appreciated.

you have to send json as a string:

require 'json'
require 'net/http'

Net::HTTP.start('192.168.1.9', 8080) do |http|
  json = {net_name: 'mynet'}.to_json
  http.post('/v2.0/networks', json, 'Content-Type' => 'application/json') do |response|
    puts response
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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