【问题标题】:Rails 5 API and Phonegap [closed]Rails 5 API 和 Phonegap [关闭]
【发布时间】:2017-04-27 02:36:12
【问题描述】:

谁能解释一下或指导我阅读详细说明如何将 Rails 5 API 连接到 Phonegap 的教程。我对 Rails 比较陌生,对 phonegap 没有经验,现在一直在寻找几天来详细解释这一点的东西。我在前端使用 HTML5、CSS 和 JQuery。

非常感谢任何帮助。

    <?xml version='1.0' encoding='utf-8'?>
<widget id="com.yourname.workshop" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0">
    <name>Workshop</name>
    <description>
        A sample Apache Cordova application that responds to the deviceready event.
    </description>
    <author email="dev@cordova.apache.org" href="http://cordova.io">
        Apache Cordova Team
    </author>
    <content src="http://localhost:3001" />
    <plugin name="cordova-plugin-whitelist" spec="1" />
    <access origin="*" />
    <allow-intent href="http://*/*" />
    <allow-intent href="https://*/*" />
    <allow-intent href="tel:*" />
    <allow-intent href="sms:*" />
    <allow-intent href="mailto:*" />
    <allow-intent href="geo:*" />
    <platform name="android">
        <allow-intent href="market:*" />
    </platform>
    <platform name="ios">
        <allow-intent href="itms:*" />
        <allow-intent href="itms-apps:*" />
    </platform>
</widget>

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-5 phonegap-build rails-api


    【解决方案1】:

    您在 Phonegap 中编写的前端应用程序与后端 Rails API “连接”的方式是使用 HTTP 请求。

    Rails has an official guide for writing API-only applications.您的应用程序不必只提供 API,但它需要提供一些易于解析的数据。 (通常是 JSON)

    然后,您使用前端的库向后端 API 定义的特定端点发出请求。然后,您可以解析响应以执行您需要执行的任何操作。 jQuery makes it easy to make requests.

    在 Rails 中,假设我有一个控制器,它允许您对某个博客或其他内容的帖子进行通常的 CRUD 操作。它可能看起来像这样:

    class PostsController < ApplicationController
      responds_to :json
    
      def show
        @post = Post.find(params[:id])
        respond_with(@post)
      end
    
      def index
        @posts = Post.all
        respond_with(@posts)
      end
    
      def create
        @post = Post.create(params[:post])
        respond_with(@post)
      end
    
      def update
        @post = Post.find(params[:id])
        @post.update_attributes(params[:post])
        respond_with(@post)
      end
    end
    

    现在您可以从 JavaScript(或其他任何东西)向这些操作发出 HTTP 请求:

    $.get('/posts', {}, function(response){
      // response here is the data returned by the Post#index action
    })
    
    $.post('/posts', {post: {content: "post content"}}, function(response){
      // response here is the data returned by the Post#create action
    })
    

    这是一个非常基本的示例,但大多数 Web 应用程序只是这个概念的一些变体。

    【讨论】:

    • 非常感谢!特别是有帮助的例子。所以理解所有这些 - 可能是一个愚蠢的问题,但我在开发时如何将控制器/服务器连接到 phonegap?我在上面的编辑中插入了我的 config.xml 文件。我添加的那条localhost 行可以解决问题吗?
    • 我自己从来没有用过phonegap,所以我不能肯定。但是,如果这为所有请求设置了域,那么它应该可以工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多