我一直试图用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函数(AJAX-data)中从data
收到calc_test
我怎样才能做到这一点?
答案 0 :(得分:0)
在您的区块中:
success: function(data){ //Sending the output to a function
console.log('success', data);
}
您可以在此处操作数据。您可以使用data.data_access
访问返回的值,并执行您喜欢的任何操作。此外,您不应该在创建操作中使用.to_json
。
答案 1 :(得分:0)
我用这种方式解决了它:
从我的控制器中调用我想在模型中使用的方法。
energy_calc_results = @calc.calc_test
并在calc_raw
添加:
return output