![](/img/trans.png)
[英]Need help in sending javascript hash to rails action through ajax call
[英]Call Rails Action to get data through Ajax
我一直在嘗試從Javascript調用我的模型,並且一半已經完成,但是我想將結果從模型中的一個方法傳遞給模型中的另一個方法,並在視圖中接收輸出。
我的模型如下:
class Calculator
def initialize( consumption, production )
@consumption = consumption
@production = production
end
def calc_raw
#Calculations
#output -> hash with outputs
end
def calc_test
raw = calc_raw
# calculation with output from calc_raw
#data -> return to AJAX.
return data
end
end
我的控制器看起來像: energycalcsb_controller.rb
class Api::V2::EnergycalcsbController < ApplicationController
skip_before_filter :verify_authenticity_token
def index
end
def create
input1 = params[:data][0].to_i
input2 = params[:data][1].to_i
@calc = Calculator.new(input1,input2)
energy_calc_results = @calc.calc_raw
render status: 200, json: {
message: "Succesful data calculation",
data_output: energy_calc_results
}.to_json
end
end
在我看來:
<script >
// Converting entries by user to integer
var myInteger1;
myInteger1 = parseInt(a); //Jahreshausverbrauch (kWh)
var myInteger2;
myInteger2 = parseInt(b); //PV-Große (kWp)
$(function () {
// Calling my API with AJAX
$.ajax({
type: 'POST',
url: '/api/v2/energycalcsb',
data: {"data":[myInteger1,myInteger2]},
dataType: 'json',
success: function(data){ //Sending the output to a function
console.log('success', data); //Help to print the output of the API
}
}); //AJAX to energy calculation module
});
</script>
我想從javascript函數中的calc_test
接收data
(AJAX數據)
我該如何實現?
在您的區塊中:
success: function(data){ //Sending the output to a function
console.log('success', data);
}
您可以在此處處理數據。 您可以使用data.data_access
訪問返回的值,並對其執行所需的任何操作。 另外,您在創建操作中不需要.to_json
。
我是這樣解決的:
從控制器中,我調用要在模型中使用的方法。
energy_calc_results = @calc.calc_test
並在calc_raw
添加:
return output
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.