php - 使用ajax刷新div

标签 php jquery ajax

当 ajax 调用成功时,我需要刷新一个选择(通过 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>

最佳答案

我的思路有两种:

  1. 像这样使用 jQuery 中的 $.load():(它是一个 GET,将响应注入(inject)您选择的节点)

$('#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);  
      }
    }
  });
});

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

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

我想有一点需要考虑的是从 div 中删除 PHP 并将此 div 变为动态的,因为页面加载了您的 Javascript。每次 AJAX 运行时,您都会终止 PHP,在运行时重写内容。

关于php - 使用ajax刷新div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35227729/

相关文章:

javascript - Nivoslider : change width and height of slider afterwards

Jquery 检查数组是否包含重复字符串

javascript - 让我们完全在客户端使用脚本标签解决跨域ajax

php - 在Symfony中找不到404路由异常处理

php - 多个站点运行共享 Zend Framework 的最佳方法?

javascript - 使用 Javascript 检查日期是否为给定格式

单击表单主体时,Ajax 控制工具包 CalendarExtender 未关闭

javascript - 如何动态加载JS、CSS文件以避免性能问题

php - 编译php扩展时出现编译错误

php - 未知的MySQL错误