首先,我正在调用一个javascript ajax函数,它将调用我转到URL时调用的ruby函数:
/ CNET
从那里开始,我想从ruby做另一个post调用,我想传递json数据。如何传递json格式的数据以在ruby中执行此调用?
我的javascript代码如下:
$.ajax({
url: "/cnet",
type: "get",
dataType: "json",
contentType: "application/json",
data: {netname:netname},
success: function(data) {
alert(data);
}
});
我的红宝石代码如下:实际上,我尝试了两种不同的方式:
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
如何传递json数据而不是字符串?
非常感谢任何帮助。
答案 0 :(得分:1)
你必须将json作为字符串发送:
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