使用Ajax刷新div

3
当ajax调用成功时,我需要刷新一个select(通过id)。但我不知道如何处理。
ajax函数:
$('#insertForm').on('click', function(){
  var form_intitule = $('input[name=form_intitule]').val();
  $.ajax({
    type: "GET",
    url: "lib/function.php?insertForm="+insertForm+"&form_intitule="+form_intitule,
    dataType : "html",
    error: function(XMLHttpRequest, textStatus, errorThrown) {
      alert(XMLHttpRequest + '--' + textStatus + '--' + errorThrown);
    },
    success:function(data){
      /*here i need to reload #listeFormation*/      }
  });
});

html.php

<div class="form-group">
  <label for="nomSalarie" class="col-sm-1 control-label" id="nameSelect">Formations</label>
  <div class="col-sm-11">
    <select name="listeFormation[]" id="listeFormation" class="form-control" multiple>';
      while($ligne = $displayFormation->fetch()){
        $data['formation'] .='<option value="'. $ligne['form_id'].'">'.$ligne['form_intitule']. " [" . $ligne['form_organisme'] . "]".'</option>';
      }
    </select>
  </div>
</div>

我的选择变为空了.. - Lucas Frugier
告诉我,如果你执行 console.log(data),你会得到什么? - Praveen Kumar Purushothaman
ReferenceError: 找不到变量:data - Lucas Frugier
什么?我不理解...:( - Lucas Frugier
你确定服务器返回了正确的HTML吗? - charlietfl
显示剩余3条评论
1个回答

0

我有两种想法:

  1. 使用jQuery的$.load()方法,例如:(它是一个GET请求,将响应注入到您选择的节点中)

$('#insertForm').on('click', function(){
  var form_intitule = $('input[name=form_intitule]').val();
  
  $("#listeFormation").load( 
    "lib/function.php", 
    { 
      insertForm: insertForm,
      form_intitule: form_intitule
    },
    function(response, status, xhr){
      if(status == "error"){
        alert(xhr + '--' + xhr.status + " " + xhr.statusText);
      }else{
        // Process the HTML you want here.. lets call: 'html_you_want_to_inject'
        
        $('#listeFormation').html(html_you_want_to_inject);  
      }
    }
  });
});

使用您的代码,您可以简单地使用:

$("#listeFormation").html(html_you_want_to_inject);

我想要思考的一个观点是将PHP从div中移除,并且在页面加载时使用JavaScript使这个div变为动态。每次AJAX运行时,您都会杀死您的PHP,并在运行时重新编写内容。


请注意,如果您在将对象传递给load()时创建POST请求而不是GET请求,则会破坏使用load()的目的。此外,如果您自己操纵响应,则也会破坏使用load()的目的。 - charlietfl
我想要注入的HTML是相同的动态列表。但是当我在.html()中编写代码时,它不起作用。 - Lucas Frugier

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接