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);
        }
      }
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Qt安装后运行不了,这是我电脑的问题吗
  • ¥15 数据量少可以用MK趋势分析吗
  • ¥15 使用VH6501干扰RTR位,CANoe上显示的错误帧不足32个就进入bus off快慢恢复,为什么?
  • ¥15 大智慧怎么编写一个选股程序
  • ¥100 python 调用 cgps 命令获取 实时位置信息
  • ¥15 两台交换机分别是trunk接口和access接口为何无法通信,通信过程是如何?
  • ¥15 C语言使用vscode编码错误
  • ¥15 用KSV5转成本时,如何不生成那笔中间凭证
  • ¥20 ensp怎么配置让PC1和PC2通讯上
  • ¥50 有没有适合匹配类似图中的运动规律的图像处理算法