0

使用 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>
4

2 回答 2

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/

于 2016-07-12T05:20:49.283 回答
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);}
    });
  });

代码笔示例

于 2016-07-12T05:29:26.957 回答