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 黄永刚的晶体塑性子程序中输入的材料参数里的晶体取向参数是什么形式的?
  • ¥20 数学建模来解决我这个问题
  • ¥15 计算机网络ip分片偏移量计算头部是-20还是-40呀
  • ¥15 stc15f2k60s2单片机关于流水灯,时钟,定时器,矩阵键盘等方面的综合问题
  • ¥15 YOLOv8已有一个初步的检测模型,想利用这个模型对新的图片进行自动标注,生成labellmg可以识别的数据,再手动修改。如何操作?
  • ¥30 NIRfast软件使用指导
  • ¥20 matlab仿真问题,求功率谱密度
  • ¥15 求micropython modbus-RTU 从机的代码或库?
  • ¥15 django5安装失败
  • ¥15 Java与Hbase相关问题