2016-07-12 6 views
0

ランダム引用符で​​Mashape APIを使用しても、クリックで何も起こりません。以下は、JSとHTMLです。 JSコードに何か問題はありますか?ボタンをクリックすると、何も起こりません。見積もりはdivには表示されません。ありがとう!jQuery APIがJavaScriptで動作しない

$('#getQuote').click(function(){ 
     $.ajax({ 
      headers: { 
      'X-Mashape-Key': 'nrXbQkfuWEmshxvDCunSMptEn0M0p1jHWCijsnX9Ow18j8TXus', 
      'Content-Type': 'application/x-www-form-urlencoded', 
      'Accept': 'application/json' 
      }, 
      method:'POST', 
      dataType: 'json', 
      url: 'https://andruxnet-random-famous-quotes.p.mashape.com/', 
      success: function(response) { 
      var ape = JQuery.parseJSON(response) 
      var quoteText = ape.quote; 
      var quoteAuthor = ape.author; 
      $(".quote").html(quoteText); 
      $(".author").html(quoteAuthor);} 
     }); 
     }); 



<body> 
    <div class = "quote">quote</div> 
    <div class = "author">author</div> 
    <div id="button"> 
    <button id="getQuote">Get Quote</button> 
    </div> 
</body> 
+0

どのコンソールエラー? – madalinivascu

+0

コードサンプルが明確ではありません。 jsは 'script'タグで囲む必要があります。そして、DOM要素にバインドできるように、ドキュメント上の関数に配置してください。 –

+0

ボタンがhtmlに入る前にjavascriptが実行されているので、jqueryがそのイベントにバインドできるようにhtmlローディングの下に置くようにしてください。 –

答えて

2

防ぐデフォルトのクリックイベント、データの解析を削除します。

$(function(){ 
    $('#getQuote').click(function (e){ 
      e.preventDefault(); 
      $.ajax({ 
       headers: { 
       'X-Mashape-Key': 'nrXbQkfuWEmshxvDCunSMptEn0M0p1jHWCijsnX9Ow18j8TXus', 
       'Content-Type': 'application/x-www-form-urlencoded', 
       'Accept': 'application/json' 
       }, 
       method:'POST', 
       dataType: 'json', 
       url: 'https://andruxnet-random-famous-quotes.p.mashape.com/', 
       success: function(response) { 
       var ape = response//remove the parsing 
       var quoteText = ape.quote; 
       var quoteAuthor = ape.author; 
       $(".quote").html(quoteText); 
       $(".author").html(quoteAuthor);} 
      }); 
      }); 
}); 

https://jsfiddle.net/cyLyn8ba/

+1

これはうまくいきましたが、今なぜ私がもっと知ってほしかったのですか?解析用ドキュメントを読む必要があります。どうもありがとう。 – Andy

+0

誰かがこの問題に遭遇した場合、[この質問](http://stackoverflow.com/questions/9111184/why-is-jquery-parsejson-not-necessary)ではJSON解析について説明し、なぜこれを含むとnullが返されるのかについて説明しています。 – Andy

1

jqueryのは、それ自体で、JSON応答を解析するのに十分なインテリジェントであるので、あなたは、機能を解析する削除する必要がありますすべてがうまくいくはずです:)

$('#getQuote').click(function(){ 
    $.ajax({ 
     headers: { 
     'X-Mashape-Key': 'nrXbQkfuWEmshxvDCunSMptEn0M0p1jHWCijsnX9Ow18j8TXus', 
     'Content-Type': 'application/x-www-form-urlencoded', 
     'Accept': 'application/json' 
     }, 
     method:'POST', 
     dataType: 'json', 
     url: 'https://andruxnet-random-famous-quotes.p.mashape.com/', 
     success: function(response) { 
     var ape = response; 
     var quoteText = ape.quote; 
     var quoteAuthor = ape.author; 
     $(".quote").html(quoteText); 
     $(".author").html(quoteAuthor);} 
    }); 
    }); 

codepen example

関連する問題