0

I have php function, that returns array to JavaScript like this:

    $data['first'] = 10;
    $data['second'] = 20;
    echo json_enocde($data);

In JavaScript the returned value is named response. I need to display the values and tried like this after reading about json:

        alert("First: " + response.first + " Second: " + response.second);

But this code only shows undefined values in places of response.first and response.second. If I write alert(response), then I get answer:

{"first":"10","second":"20"}

This means, that JavaScript is getting the information. How can I get the values separately from the json encoded array?

Regards

4

3 回答 3

2

用于JSON.parse()将 JSON 字符串转换为 JavaScript 对象。

于 2012-10-16T12:12:18.100 回答
0

看起来您仍然有 JSON 字符串,并且没有将其解析为 JS 对象。使用JSON.parse

var jsonString = '{"first":"10","second":"20"}'; // from whereever
var obj = JSON.parse(jsonString);
alert("First: " + response.first + " Second: " + response.second);
alert(obj); // should now be "[object Object]"
于 2012-10-16T12:14:23.043 回答
-2

使用 eval like(不推荐)

var res = eval(response); //as you can see people are against it so I am editing the answer

使用 JSON.parse()

或者如果你使用 jquery

jQuery.parseJSON(response);
于 2012-10-16T12:12:36.370 回答