如何以json格式传递数据以在ruby中进行ajax post调用? [英] how to pass data in json format to do an ajax post call in ruby?
问题描述
首先,我正在调用一个javascript ajax函数,该函数将调用当我转到URL时被调用的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
/cnet
从那里,我想从ruby进行另一次调用,在其中我要传递json数据.如何传递json格式的数据以在ruby中进行此调用?
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?
我的JavaScript代码如下:
My javascript code is the following:
$.ajax({
url: "/cnet",
type: "get",
dataType: "json",
contentType: "application/json",
data: {netname:netname},
success: function(data) {
alert(data);
}
});
我的ruby代码如下:实际上,我以两种不同的方式对其进行了尝试:
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
如何传递json数据而不是字符串?
How do I pass json data instead of a string?
任何帮助将不胜感激.
推荐答案
您必须将json作为字符串发送:
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
这篇关于如何以json格式传递数据以在ruby中进行ajax post调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!