doskmc7870 2015-06-27 00:12
浏览 23
已采纳

在Rails中服务PHP

I have a small PHP service that is being called in a JavaScript file by AJAX :

$.ajax({
    type: "GET",
    url: "getDate.php",                 
    dataType:"json",
    data :{
        fromDate:fromDate,
        toDate:toDate
    },
    success: function(data) {
         ......
        }
});

This service contains :

$fromDate = $_GET['fromDate'];
$toDate = $_GET['toDate'];
$fromDate=date_create($fromDate);
$fromdate = date_format($fromDate,"Y-m-d")."T".date_format($fromDate,"H:i:s")."Z";
$fromdate = urlencode($fromdate);
$toDate=date_create($toDate);
$todate = date_format($toDate,"Y-m-d")."T23:00:00Z";
$todate = urlencode($todate);
$url = "http://194.209.53.19:8086/query?db=Bellevue&q=select+*+from+measures+where+time%3E%3D%27".$fromdate."%27+and+time%3C%3D%27".$todate."%27";
$data = file_get_contents($url, false);
echo $data;

I need to use this in my Rails application. I was wondering if I could put the .php file in a Rails folder, and simply call it. Or if there's a way to do a similar service in Rails?

  • 写回答

1条回答 默认 最新

  • dqsa17330 2015-06-27 00:50
    关注

    Sure, you can do this in Rails. First, you need to define the route for your request. Write the following in your routes.rb file, located at config/routes.rb:

    get "/getDate" => "generals#get_date"
    

    What that means is: whenever there is a GET request for /getDate, go to controller GeneralController, and invoke its function named get_date. If you wrote users#get_date, Rails would try to find the get_date method in UsersController.

    Generate the controller of your choice by following command:

    rails generate controller General
    

    It will generate a file named general_controller.rb in app/controller among other files.

    Now, you need to define all your logic there. Other thing: in PHP, you get the sent data using $_GET['formDate'], but in Rails, you will accomplish the same functionality by doing params[:formDate].

    def get_date
      form_date = params[:formDate]
      # and now here you can write all your logic, and can finally return the response
    
      respond_to do |format|
        format.json { render json: data_to_be_returned } 
      end
    end
    

    Edit:

    For date_create or date_format functions in PHP, you can look up their equivalents at here and here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同