单击按钮时$ .getJSON请求不起作用

时间:2017-05-15 07:50:59

标签: javascript jquery html json api

嘿伙计们,我试图找到解决这个问题的办法,我目前不知所措。我正在尝试使用twitch API收集关于流的信息。

当我传入用户名数组时,我能够获得.getJSON请求,如果用户离线或无效,则返回null。



$(document).ready(function() {
  var streamers = ["ESL_SC2","OgamingSC2","cretetion","freecodecamp","storbeck","habathcx","RobotCaleb","noobs2ninjas","meteos","c9sneaky","JoshOG"];
  var url = "https://api.twitch.tv/kraken/streams/";
  var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";

  getInitialStreams(streamers, url, cb); //load hard-coded streams
});

function getInitialStreams(streamers, url, cb) {
  //loop through the streamers array to add the initial streams
  for (var i = 0; i < streamers.length; i++) {
    (function(i) {
      $.getJSON(url + streamers[i] + cb, function(data) {
        //If data is returned, the streamer is online
        if (data.stream != null) {
          console.log("online");
        } else {
          console.log("offline");
        }
      });
    })(i);
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
      <input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
      <button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>
&#13;
&#13;
&#13;

但是,当我尝试通过单击函数调用API时(最终通过表单拉取任何输入).getJSON失败。如下所示。

&#13;
&#13;
$(document).ready(function() {
  var url = "https://api.twitch.tv/kraken/streams/";
  var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";

  $("#addStreamerBtn").click(function(e) {
    addStreamer("Ben", url, cb);
  });
});

function addStreamer(streamer, url, cb) {
  console.log("I'm inside the function");
  $.getJSON(url + streamer + cb, function(data) {
    console.log("WE DID IT");
  });
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
  <input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
  <button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>
&#13;
&#13;
&#13;

我不明白为什么代码不适用于第二段代码。任何指导都将不胜感激。

1 个答案:

答案 0 :(得分:2)

问题是因为您已经挂钩了提交按钮的click事件。这意味着在您的AJAX请求发生时正在提交form,因此页面立即被卸载并且AJAX被取消。

要解决此问题,请暂停submit的{​​{1}}事件,并在事件上调用form。试试这个:

preventDefault()
$(document).ready(function() {
  var url = "https://api.twitch.tv/kraken/streams/";
  var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";

  $(".form-inline").submit(function(e) {
    e.preventDefault();
    addStreamer("Ben", url, cb);
  });
});

function addStreamer(streamer, url, cb) {
  console.log("I'm inside the function");
  $.getJSON(url + streamer + cb, function(data) {
    console.log("WE DID IT");
  });
}