2013-10-19 35 views
0

首先,我調用JavaScript的AJAX功能,將來電,當我去到URL,它被稱爲紅寶石功能:如何通過json格式傳遞數據在ruby中做ajax post調用?

/CNET

從那裏,我想從ruby中做另一個我想傳遞json數據的郵件。如何通過json格式的數據在ruby中執行此調用?

我的javascript代碼如下:

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

我的Ruby代碼如下:事實上,我試圖在兩種不同的方式:

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

接受。我喜歡。非常感謝carolclarinet。 –

回答

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 
+0

它的工作。 json use中的一個小改動=>而不是:。 –

+0

你的意思是像'{'net_name'=>'mynet'}'? – phoet

相關問題