2017-02-21 3 views
2

Событие onClick() кнопки не направляется в любом месте. Возможно, возникла некоторая проблема с успехом() ajax.I не могу понять, что, поскольку я новичок к этому.Ajax success() не работает при вызове API

var currentAuthor=""; 
var currentQuote=""; 
$(document).ready(function(){ 
    $("#getMessage").on("click",function(){ 
    $.ajax({ 
    header:{ 
     "X-Mashape-Key":"xE5Raw3acMmsh4dpp6HEk5WSbJtTp1X9TL3jsnue3VRzr5vNNa", 
    Accept: "application/json", 
     "Content-Type": "application/x-www-form-urlencoded" 
    }, 
    url:"https://andruxnet-random-famous-quotes.p.mashape.com/?cat=", 
    success: function(response){ 
     var r=json.parse(response); 
     currentQuote=r.quote; 
     currentAuthor=r.author; 
     $("#author").html(r.author); 
    } 
    }); 
    }); 
}); 
+0

Получаете ли вы какие-либо ошибки в консоли? – Hodrobond

+0

Я попытался скопировать код в скрипку, и я получил 401, заголовок «X-Mashape-Key» никогда не добавляется – Nicolas

+0

Итак, что я должен делать? @Hodrobond – aayushi

ответ

5

У вас было 2 проблемы:

  1. заголовок должен быть headers
  2. это JSON.parse и не json.parse

var currentAuthor = ""; 
 
var currentQuote = ""; 
 
$(document).ready(function() { 
 
\t $("#getMessage").on("click", function() { 
 
\t \t $.ajax({ 
 
\t \t \t headers: { 
 
\t \t \t \t "X-Mashape-Key": "xE5Raw3acMmsh4dpp6HEk5WSbJtTp1X9TL3jsnue3VRzr5vNNa", 
 
\t \t \t \t "Accept": "application/json", 
 
\t \t \t \t "Content-Type": "application/x-www-form-urlencoded" 
 
\t \t \t }, 
 
\t \t \t url: "https://andruxnet-random-famous-quotes.p.mashape.com/?cat=", 
 
\t \t \t success: function (response) { 
 
\t \t \t \t var r = JSON.parse(response); 
 
\t \t \t \t currentQuote = r.quote; 
 
\t \t \t \t currentAuthor = r.author; 
 
\t \t \t \t $("#author").html(r.author); 
 
\t \t \t } 
 
\t \t }); 
 
\t }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button id="getMessage">Get Message</button> 
 
<p id="author"></p>

+0

это сработало! Благодаря! @ Z-Bone – aayushi

+0

@aayushi Уверенная вещь :) –

Смежные вопросы