2017-04-05 62 views
0

這可能是一個愚蠢的問題,但是你能告訴我如何在我的Bootstrap頁面中從我現有的Rails JSON-API服務器調用'端點'。 Bootstrap頁面是否必須位於API服務器的視圖文件夾中,如果有的話,我該如何調用控制器並將接收到的JSON放入我的前端元素中?從Bootstrap前端調用Rails JSON-API

謝謝你現在,我希望你明白我的意思。

+0

你到目前爲止嘗試過什麼?你有沒有做過可以和我們分享的研究成果? –

回答

0

考慮的blogs的支架爲例與rails routesrake routes),你可以看到,在中定義的所有的「端點」你routes.rb

Prefix Verb URI Pattern     Controller#Action 
    blogs GET /blogs(.:format)    blogs#index 
      POST /blogs(.:format)    blogs#create 
new_blog GET /blogs/new(.:format)   blogs#new 
edit_blog GET /blogs/:id/edit(.:format)  blogs#edit 
    blog GET /blogs/:id(.:format)   blogs#show 
      PATCH /blogs/:id(.:format)   blogs#update 
      PUT /blogs/:id(.:format)   blogs#update 
      DELETE /blogs/:id(.:format)   blogs#destroy 

如果你看到blogs GET /blogs(.:format) blogs#index是給你所有的blogs通過GET請求。

您應該會從你的API的所有blogs

使用普通的JavaScript

var request = new XMLHttpRequest(); 
request.open('GET', 'localhost:3000/blogs', true); 

request.onload = function() { 
    if (request.status >= 200 && request.status < 400) { 
    var data = JSON.parse(request.responseText) 
    ... 
    } else { 
    ... 
    } 
}; 
request.onerror = function() { 
    ... 
}; 
request.send(); 

而且使用Javascript fetch

fetch('localhost:3000/blogs', { 
    ... 
}).then(function(response) { 
    console.log(response) 
}).catch(function(err) { 
    console.log(err) 
}); 

使用jQuery:

$.ajax({ 
    url: 'localhost:3000/blogs', 
    dataType: 'script', 
    success: function(result) { 
    console.log(result) 
    }, 
}); 

然後,您可以根據需要繼續插入,更新和/或刪除數據。

+0

謝謝,這很有幫助! – mfaorlkzus

1

你可能想看看rake routes這會告訴你可用的路線。

所以基本上會做一個請求客戶端,也許在某些js到一個特定的端點,然後該端點將返回數據,你可以做任何你想要的客戶端。

你很可能不會從你的視圖中調用你的端點,通常你會有一個單獨的js文件,但如果你真的想,可以添加一些js到你的視圖並直接從那裏調用你的端點。