jQuery API 不适用于 JavaScript



使用Mashape API进行随机报价,但点击时没有任何反应。下面是JS和HTML。JS代码有问题吗?当我单击按钮时,没有任何反应。报价未出现在div中。 谢谢!

$('#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>

阻止默认的点击事件,删除数据的解析:

$(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/

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);}
    });
  });

代码笔示例

相关内容

  • 没有找到相关文章

最新更新