duanjian3338 2013-07-25 13:04
浏览 38
已采纳

如何在不同的dom元素中用ajax显示数据?

i want to display data that the Ajax function receive from php file into different HTML elements.

function getdetails(x)
{

if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("fname").value=xmlhttp.responseText;

     }
  }
  • 写回答

1条回答 默认 最新

  • donglun2010 2013-07-25 13:11
    关注

    Use jQuery for this:

    $.ajax({
       type:'GET', 
       url:'url/to/the/file.php',
    }.done(function( msg ) {
       $('#id-of-element').html(msg);
       $('.class-of-other-element').html(msg); // another element
       $('.class-of-another-element').html(msg); // another element
    });
    

    Explanation:

    type: GET // type of http request to the file, could also be POST 
    
    url: 'url/to/the/file.php' // provide the file and path to file to communicate with
    
    .done (function(msg)) {  // when ajax request is completed (if), then assign the variable 'msg' with the contents of the return.
    
    $('#id-of-element').html(msg); // assign the return data to the html element of your choice. 
    

    EDIT:

    If you're expecting 2 variables, in the PHP file return them like this:

    echo $var1."/".$var2  // where '/' is a symbol you never expect to be returned in either variable. 
    

    Then in your Ajax:

    $.ajax({
       type:'GET', 
       url:'url/to/the/file.php',
    }.done(function( msg ) {
       var content = msg; 
       var varSplit = msg.split('/'); //where '/' is the symbol you chose to use in the stage above.
       var var1     = varSplit[0];
       var var2     = varSplit[1];
       $('.first-element').html(var1);
       $('.second-element').html(var2);
    }); 
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址