2017-04-27 57 views
0

任何人都可以解释如何或指导我的教程,详细解释如何将Rails 5 API连接到Phonegap。我对Rails比较陌生,没有phonegap方面的经验,现在已经在寻找几天了解详情。我在前端使用了HTML5,CSS和JQuery。Rails 5 API和Phonegap

真的很感谢任何帮助。

<?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="[email protected]" 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> 

回答

2

将您在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 

现在,您可以发出HTTP请求从JavaScript这些动作(或其他任何东西,对这个问题):

$.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 
}) 

这是一个非常简单的例子,但大多数网络应用程序只是这个概念的一些变体。

+0

非常感谢!特别是帮助的例子。所以理解所有这些 - 可能是一个愚蠢的问题,但是我在开发过程中如何将控制器/服务器连接到phonegap?我在上面的编辑中插入了我的config.xml文件。我添加的'localhost'这行是否有诀窍? – dgreen22

+0

我从来没有使用phonegap,所以我不能肯定地说。但是,如果这为所有请求设置了域,那么它应该可以工作 – Brennan