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

时间:2012-04-18 09:39:36

标签: php ajax

我想从submit.php页面获取数据并将它们放在我页面中的某些标签中。在下面的示例中,我可以只将标签中的数据放在id:“shortcutTitle”中。 我从我的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();
}

1 个答案:

答案 0 :(得分:3)

您可能希望使用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);
}
相关问题