douruoshen1449 2017-02-22 01:28
浏览 26
已采纳

JS Ajax OnClick:如何多次执行php代码?

I have an html button with an onclick attribute which runs a jQuery AJAX function pointing to php code.
The php code writes HTML in an output HTML <select> element(the element remains hidden until the javascript runs.)
This is working great to populate the <select> when an "add another" button is clicked.

The problem is it adds one and only one. I want to be able to have a new <select> tag populate with each click of the "add another" button up to a max of 2.
The JS in question:

var genre_dropdown = function genre_dropdown() {
  $('.genre_output').css('display', 'block');
  $.ajax({
      url:'../includes/functions/genre_dropdown.php',
      complete: function (response) {
      $('.genre_output').html(response.responseText);
      },
      error: function () {
          $('.genre_output').html('Bummer: there was an error!');
      }
  });
  return false;
}


The HTML in question:

  <select name="genre_id[]" autocomplete="off" class="genre_output"></select>
  <select name="genre_id[]" autocomplete="off" class="genre_output"></select>
  <div class="button add-genre-button" onclick="return genre_dropdown();">+ Add Existing Genre</div>


I thought I could include 2 html <select> elements for the php to populate into, the code would execute from one to the next. I see why this is not correct, the code is running in both at the same time. I'm at a place where I'm considering have 2 buttons ("add one", "add another") but that seems redundant and not correct, especially considering I want a scale-able technique (the max may not always be 2.) I need help.

  • 写回答

2条回答 默认 最新

  • duafagm1066 2017-02-22 02:34
    关注

    Your php request is fine.

    I simply mean define a variable as your using javascript i.e.:

    var sel = '<select name="genre_id[]" autocomplete="off" class="genre_output">' + response + "</select>';
    

    and then each time you do a request it will include the response as the value of the element. This would allow you to append the parent div as many times as you want. Finally, use a simple if counter to decide whether to keep appending or not:

    if ($(".genre_output").length <= 2){
       $("PARENT_DIV_ID").append(sel);
    };
    

    Is this clearer? @kaari

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么