Railsで自作APIを作りました。
それをAjaxを使ってクライアント側で処理しようと思い、試しに以下のコードを作成しました。
正常に動けば、APIからのレスポンスデータを使ってテキストを変更するコードです。
しかし、自作APIからのレスポンスデータでテキストを変更できませんでした。
比較のため他のサービスのAPIからのレスポンスデータで試みたところ正常にテキストが変更されました。
ブラウザでリクエストを送ると自作APIからもjsonデータが返ってきているみたいなのでAPIサーバ側は正常に動いていそうで原因がわからず困っております。
どこに問題があるのでしょうか。
html
1 2<!DOCTYPE html> 3<html> 4<head> 5 <title>API</title> 6 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 7</head> 8<body> 9<button class="btn">btn</button> 10<h1 class="text">text</h1> <!-- 変更するテキスト--> 11<script type="text/javascript"> 12$(document).ready(function(){ 13 const url = 'https://floating-crag-25693.herokuapp.com/timecards'; // 自作API 14 //const url = 'https://jsonplaceholder.typicode.com/posts'; // 比較用API 15 $('.btn').click(function(){ 16 $.ajax({ 17 url: url, 18 type:"GET", 19 success: function(result){ 20 $('.text').text(`${result}`); 21 }, 22 error:function(error){ 23 console.log(`Error ${error}`); 24 } 25 }) 26 }) 27}) 28</script> 29</body> 30</html>
参考までにrailsのコードの一部も掲示します。
ruby
1class TimeCardsController < ApplicationController 2 def index 3 @timecards = TimeCard.all 4 render json: @timecards 5 end 6 7 def show 8 @timecard = TimeCard.find(params[:id]) 9 render json: @timecard 10 end 11 12 def create 13 @timecard = TimeCard.new(state:params[:state]) 14 15 if @timecard.save 16 render json: @timecard, status: :created, location: timecards_url(@timecard) 17 else 18 render json: @timecard.errors, status: :unprocessable_entity 19 end 20 end 21 22 23 private 24 25 def timecard_params 26 params.fetch(:timecards, {}).permit(:state) 27 end 28end
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/10/25 14:12