如何使用 ajax 从 php 文件中获取多个数据


How can I get multiple data, from a php file, with ajax?

我想从 submit.php 页面获取数据,并将它们放在我页面的一些标签中。 在下面的示例中,我可以只在具有 id 的标签中放置数据:"快捷方式标题"。我从我的php文件(从数据库)中获取多个数据,我希望它们位于我页面中的各种标签上。

function submit(shortcutid,shortcuttitle,shortcutlink,icon)
{
    var xmlhttp;
    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("shortcutTitle").value=xmlhttp.responseText;
        }
    }
    xmlhttp.open("GET","submit.php?shid="+shortcutid+"&shtitle="+shortcuttitle+"&shlink="+shortcutlink+"&shicon="+icon,true);
    xmlhttp.send();
}
您可能

希望使用 json_encode 将 javascript 对象发送回 XML 请求

<?php
  echo json_encode( array('name' => 'tehlulz', 'id' => '1') );
?>

因此,从结果中,您可以通过以下方式调用输出:

var ajaxResuts = {};
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
  ajaxResuts = JSON.parse( xmlhttp.responseText );
  alert("Returned: " + ajaxResults.name);
}