0

我有返回数组的页面 getorgname.php 那么如何使用 $.ajax 方法在我的 jquery 页面中获取数组?

$ds = my_ldap_connect(CHI_LDAP_LOCATION, CHI_LDAP_PORT, CHI_LDAP_USE_TLS);
$groups = get_all_groups($ds, CHI_LDAP_BASE_DN, CHI_LDAP_BIND_DIRECTORY, CHI_LDAP_BIND_PASSWORD);
$sr = @ldap_search($ds, "ou=people,".CHI_LDAP_BASE_DN, "(uid=*)");
$nt = ldap_get_entries( $ds, $sr );
//echo "<pre>";
//print_r($nt);
//echo "</pre>";
foreach( $nt as $each )
{
    if( is_array( $each ) )
    {

        $json[] = trim('"'.$each['o'][0].'"');

    }
}

返回 $json;

4

2 回答 2

2

设置正确的 json 标头以提供 json 并以 json 格式打印数组:

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json'); 

//create your array here

echo json_encode(array);

然后在客户端使用 jQuery 接收数组:

$.ajax({
   url: 'getorgname.php',
   dataType: 'json',
   success: function(data){
       //the 'data' object contains your array
       //do stuff with it here
   }
});
于 2013-03-01T15:06:40.790 回答
1

无需在 jQ 的$.ajax调用中设置数据类型,只需使用echo构造而不是 then return,就可以了。如果您开始弄乱标头,您迟早会遇到麻烦:
您只能在尚未生成任何输出的情况下设置标头,所以请注意:要么缓冲,要么将header调用保持在最顶部。只知道你在做什么

在您的情况下,仅以结尾echo json_encode($json);就可以了:

foreach( $nt as $each )
{
    if( is_array( $each ) )
    {
        $json[] = trim($each['o'][0]);
    }
}
echo json_encode($json);

这就是您需要做的所有事情,您不必手动格式化 JSON。
你的 jQ 应该是这样的:

$.ajax({
    url: 'yourscript.php',
    data: yourRequestObject,
    success: function(response)
    {
        console.log(response);//this'll be either an array or an object (assoc array's are objects in JS)
    }
});
于 2013-03-01T15:43:13.017 回答