weixin_33720956 2017-10-24 16:07 采纳率: 0%
浏览 41

jQuery / Ajax有时会失败

Have been working on a small project. For some reason, sometimes my Ajax/JQuery functions don't execute.

For example, I have a button that once you click it, an automatic select/option list is generated from SQL of employee names. I am setting it up as such:

$("#search_prospects_image").one('click', function() {
  var blankData;
  $.post('get_prospects.php', blankData, processData);

  function processData(data) {
    var prospect_names = JSON.parse(data);
    var select = document.getElementById("search_prospects_image");

    for (var i = 0; i < prospect_names.length; ++i) {
      var option = document.createElement("option");
      option.text = prospect_names[i];
      option.value = prospect_names[i];
      select.appendChild(option);
    }
  }
});

Occasionally, when I click the button and attempt to select an option, it doesn't list anything. I need to either refresh the page, or click something else, and then go back to it.

I am not an expert by any means - fairly new at this, so I wouldn't be surprised if I was doing this incorrectly.

If anyone can see anything off the bat that would slow down these calls or sometimes make them fail, I would love to know! Thanks!

  • 写回答

1条回答 默认 最新

  • 斗士狗 2017-10-24 16:13
    关注

    You're using one():

    Description: Attach a handler to an event for the elements. The handler is executed at most once per element per event type.

    So it's only going to fire on the first click.

    You probably want on()

    Description: Attach an event handler function for one or more events to the selected elements.

    So it will execute the call on each and every click.

    As far as your code; I would just reflect that one change:

    $("#search_prospects_image").on('click', function() {
      var blankData;
      $.post('get_prospects.php', blankData, processData);
    
      function processData(data) {
        var prospect_names = JSON.parse(data);
        var select = document.getElementById("search_prospects_image");
    
        for (var i = 0; i < prospect_names.length; ++i) {
          var option = document.createElement("option");
          option.text = prospect_names[i];
          option.value = prospect_names[i];
          select.appendChild(option);
        }
      }
    });
    
    评论

报告相同问题?