2017-09-06 14 views
-1

私はこのAPIからランダムな見積もりを引き出すための簡単なget要求を行っています。ボタンのクリックで見積もりを変更するハードコーディングがうまくいきます。単純なAPI要求が機能しない

$(document).ready(function() { 
 
    $("#quotebtn").on('click', function(e) { 
 
    e.preventDefault(); 
 
    $.ajax({ 
 
     type: 'GET', 
 
     url: 'http://quotes.stormconsultancy.co.uk/random.json', 
 
     success: function(data) { 
 
     var post = data.shift(); //get the first quote 
 
     $('#quote').html(post.content); //change the html to the quote 
 

 
     }, 
 
     cache: false 
 
    }); 
 
    // $("#quote").html("You clicked!"); 
 
    }) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="body"> 
 
    <h1>Quote Machine</h1> 
 
    <div id="quote">Here is the quote</div> 
 
    <button id="quotebtn" type="button" class="btn btn-primary"> 
 
    Button 
 
    </button> 
 
</div>

+0

はあなたがコンソールでどのようなエラーを取得していますか? –

+0

jquery.min.js:4混在コンテンツ: 'https://codepen.io/stepup2stepout/pen/gxZVWz?editors=1010'のページがHTTPS経由で読み込まれましたが、安全でないXMLHttpRequestエンドポイント 'http:// quotes .stormconsultancy.co.uk/random.json?_ = 1504721878738 '。このリクエストはブロックされました。 HTTPS経由でコンテンツを配信する必要があります。 –

答えて

1

解説に基づいて:Mixed Content: The page at 'codepen.io/stepup2stepout/pen/gxZVWz?editors=1010'; was loaded over HTTPS... HTTPとHTTPSを混在させないでください。あなたが照会しているページには安全な相手がいません。

混在したコンテンツは別として、サーバの応答は配列ではなく、オブジェクトであり、オブジェクトではありません。.shift()オブジェクト、配列のみです。代わりの

function(data) { 
    var post = data.shift(); //get the first quote 
    $('#quote').html(post.content); //change the html to the quote 
    } 

試してみてください。

function(data) { 
    $('#quote').html(data.quote); //change the html to the quote 
    } 

Mixed Content (MDN)

+0

恐ろしい、助けてくれてありがとう! –

0

APIから戻されるデータ。

{ 
    "author": "Charles Babbage", 
    "id": 8, 
    "quote": "On two occasions I have been asked, \u2018Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?\u2019 I am not able rightly to apprehend the kind of confusion of ideas that could provoke such a question.\u201d", 
    "permalink": "http://quotes.stormconsultancy.co.uk/quotes/8" 
} 

これは配列ではないので、data.shift()を行う必要はありません。 しています。
$('#quote').html(data.quote); で十分です。

0

APIは、配列ではなく単一のJSONオブジェクトを返しています。したがって、シフト操作を行う必要はありません。

以下のコードはあなたのためのトリックを行う必要があります。

$(document).ready(function() { 
$("#quotebtn").on('click', function(e) { 
    e.preventDefault(); 
    $.ajax({ 
     type: 'GET', 
     url: 'http://quotes.stormconsultancy.co.uk/random.json', 
     success: function(data) { 
      var post = data.quote; //get the first quote 
      $('#quote').html(post); //change the html to the quote 
     }, 
     cache: false 
    }); 
    }) 
}) 
関連する問題