无法使用javascript打印AJAX返回的数组

时间:2011-02-22 11:26:20

标签: php javascript ajax

function getWriters(cat, lev, id)   
{
    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("writer").innerHTML = xmlhttp.responseText;
            var writer = eval(xmlhttp.responseText);
            document.write(writer)
        }


    }

    xmlhttp.open("GET", "order.php?op=2&id=0&cat=" + cat + "&lev=" + lev, true);
    xmlhttp.send();


}

xmlhttp.responseText返回

Array ( [0] => Array ( [name] => Unassigned [user_id] => 2 [writing_level] => [writing_category] => ) [1] => Array ( [name] => arsalan [user_id] => 3 [writing_level] => [writing_category] => ) [2] => Array ( [name] => Shazia [user_id] => 4 [writing_level] => [writing_category] => ) [3] => Array ( [name] => janea [user_id] => 5 [writing_level] => [writing_category] => ) [4] => Array ( [name] => s [user_id] => 6 [writing_level] => [writing_category] => ) [5] => Array ( [name] => iuiui [user_id] => 8 [writing_level] => [writing_category] => ) [6] => Array ( [name] => demo [user_id] => 9 [writing_level] => [writing_category] => ) [7] => Array ( [name] => wewe [user_id] => 10 [writing_level] => [writing_category] => ) [8] => Array ( [name] => Muhammad Zoyeb [user_id] => 11 [writing_level] => [writing_category] => ) [9] => Array ( [name] => Atif Rauf Alvi [user_id] => 12 [writing_level] => [writing_category] => ) [10] => Array ( [name] => demo-1 [user_id] => 13 [writing_level] => [writing_category] => ) [11] => Array ( [name] => ffff** [user_id] => 14 [writing_level] => High School,Masters [writing_category] => Literature and Language,Social Sciences ) ) 

我在document.write(writer)上遇到语法错误; 如果我删除eval(),则没有语法错误。

任何人都可以解释如何解决这个或其他一些方法来转换返回到数组的字符串。

谢谢

3 个答案:

答案 0 :(得分:3)

从服务器返回的字符串不是有效的JSON或JavaScript语法,因此您无法将其传递给eval()。看起来你在服务器上的数组上使用PHP的print_r函数 - 你需要使用json_encode(PHP> 5.2):

echo json_encode($myArray);

然后,您可以使用JSON.parse(推荐)或eval在本地解析。

答案 1 :(得分:0)

看起来你的JSON响应是PHP数组的字符串化版本。为什么不从PHP返回JSON,然后Javascript本地获取数组。

答案 2 :(得分:0)

您正在返回数组的PHP“表示”,并且通过评估此字符串,您将陷入语法错误。

试试这个:

  • 以逗号分隔的字符串
  • 从PHP返回数组
  • 在JS中分解字符串并将其放入数组中(如果需要JS数组,否则打印并停止)

要拆分字符串,请使用:

var response = xmlhttp.responseText;
var responseArray = response.split(",");