-2

我想将 Ajax 函数从 php 文件接收到的数据显示到不同的 HTML 元素中。

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;

     }
  }
4

1 回答 1

1

为此使用jQuery :

$.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
});

解释:

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. 

编辑:

如果您期望 2 个变量,请在 PHP 文件中像这样返回它们:

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

然后在你的 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);
}); 
于 2013-07-25T13:11:27.227 回答