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 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)