简体   繁体   English

调用Rails Action通过Ajax获取数据

[英]Call Rails Action to get data through Ajax

I have been trying to call my model from Javascript and the half is already done, but I want to pass the results from one method in my model to another method in my model and the receive the output in my view. 我一直在尝试从Javascript调用我的模型,并且一半已经完成,但是我想将结果从模型中的一个方法传递给模型中的另一个方法,并在视图中接收输出。

My model looks like: 我的模型如下:

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

My controller looks like: energycalcsb_controller.rb 我的控制器看起来像: 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

In my view: 在我看来:

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

I want to receive the data from calc_test in my javascript function (AJAX-data) 我想从javascript函数中的calc_test接收data (AJAX数据)

How can I achieve this? 我该如何实现?

In your block: 在您的区块中:

success: function(data){ //Sending the output to a function
  console.log('success', data);
}

You can operate on the data right here. 您可以在此处处理数据。 You can access your returned value with data.data_access , and perform any action you like upon it. 您可以使用data.data_access访问返回的值,并对其执行所需的任何操作。 Also, you shouldn't need the .to_json in your create action. 另外,您在创建操作中不需要.to_json

I solved it in this way: 我是这样解决的:

From my controller I call the method I want to use in my model. 从控制器中,我调用要在模型中使用的方法。

energy_calc_results = @calc.calc_test

and in calc_raw add: 并在calc_raw添加:

  return output

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM