将php数组值转换为javascript数组

时间:2012-04-09 07:06:01

标签: php jquery

我需要在php中返回一个数组并在javascript中使用它。当我打印返回的值时,它打印空字符串。我怎么弄错了?

$.ajax({
     type: "POST",
     url: "sort2.php",    
     success: function(result){      

     alert(result[0]);                                            

    }
});

// sort2.php

$data[0] = "book";
$data[1] = "pen";
$data[2] = "school";
echo json_encode($data);

4 个答案:

答案 0 :(得分:3)

您可以将dataType请求的$.ajax()更改为json,让jQuery自动从字符串中解码您的JSON对象。

或者,您可以添加到PHP header('Content-Type: application/json'),jQuery也应该自动解码您的JSON字符串。

答案 1 :(得分:1)

您必须解析JSON数据

$.ajax({
     type: "POST",
     url: "sort2.php",    
     success: function(result){      

     //Parse Json to Array 
     result = jQuery.parseJSON(result);
     alert(result) // would output the result array                                      

    }
});

答案 2 :(得分:1)

sort2.php文件中,更改以下代码:

echo json_encode($data);

header('Content-Type: application/json');
echo json_encode($data);

它的作用是告诉客户端浏览器将响应视为JSON数据并进行相应的解析,而不是HTML,这是默认值。

此外,请确保sort2.php文件与您进行ajax调用的html文件位于同一文件夹中。

希望这有帮助。

答案 3 :(得分:1)

你也可以使用jQuery的$ .post方法,它看起来像这样:(所以你不需要改变你的php脚本,请看这里:jQuery Post)。

$.post(
    'sort2.php', //script you request
    {}, //post-data you want to send
    function(result) {
        alert(result[0]); /*i like more: console.log(result); this way you can see it in firebug e.g.) */
    },
    'json' //data-type you expect
);