简体   繁体   English

完成我的第一个AJAX呼叫-卡住了为什么我的结果根本不显示的原因

[英]Working through my first AJAX call - Stuck as to why my results aren't displaying at all

Test it here - http://paulmatheson.net/webdev/wiki/wikipedia-viewer.html 在此处进行测试-http://paulmatheson.net/webdev/wiki/wikipedia-viewer.html

Basically, you enter a term and the results are supposed to display below. 基本上,您输入一个术语,结果应该显示在下面。 I had it working for a second but changed something in the last hour or so and don't know where I screwed up. 我让它工作了一秒钟,但是在最后一个小时左右改变了一些东西,不知道我在哪里搞砸了。 I've analyzed it and can't find the issue in the code. 我已经分析过了,在代码中找不到问题。 Can someone with a better eye/more experience help me out? 拥有更好视力/更多经验的人可以帮助我吗?

$(document).ready(function() {
  $('#random-btn').click(function() {
    window.open('https://en.wikipedia.org/wiki/Special:Random');
  });
  $('#submit-search-btn').click(function() {
    var searchTerm = $('#search-input').val();
    var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchTerm + "&format=json&callback=?";

    $.ajax({
      type: "GET",
      url: url,
      async: false,
      dataType: "json",
      success: function(data) {
        var html;
        $('#header').html('<h5>Wiki Search</h5');
        $('.content').css('margin-top', '0');
        $('#div-random-btn').remove();

        for (var i = 0; i < data[1].length; i++) {
          html += "<div class='listing'><h4>" + data[1][i] + "</h4><h5>" + data[2][i] + "</h5></div>";
        };

        $("#output-div").html(html);
      },
      error: function(errorMessage) {}
    })
  })
});

That is the gist of the call. 这就是呼吁的要旨。 Please let me know if anything needs a more thorough break down. 请让我知道是否需要更彻底的分解。

It is because your button is form element & its type is submit . 这是因为您的button是表单元素,其类型是submit So basically what's wrong is the form is submitted via form. 所以从根本上说,表单是通过表单提交的。 Your ajax call is being cancelled due to this & page is reloading. 由于此&页面正在重新加载,您的ajax呼叫被取消。 You can do two things 你可以做两件事

  1. You need to stop this event by using preventDefault method on button click like this 您需要通过在这样的按钮单击上使用preventDefault方法来停止此事件

    $('#submit-search-btn').click(function(e) { e.preventDefault() var searchTerm = $('#search-input').val(); //Further code

  2. Change the button attribute to type="button" which will stop it from submitting in the first place 将button属性更改为type="button" ,这将阻止它首先提交

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM