将ajax的值存储到javascript变量中


Store value of ajax into a javascript variable

我有一个php文件,从服务器获取数据。php文件的输出是一个变量,包含json格式的数据。

PHP文件:

<?php 
$dbHostName = "localhost";
$dbUserName = "venseld";
$dbUserPass = "wecuuu";
$dbName = "veseldb";
try
{
    global $dbHostName, $dbUserName, $dbUserPass, $dbName;
    $pdo = new PDO("mysql:host=$dbHostName;dbname=$dbName", $dbUserName, $dbUserPass);  
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  
    $statement = $pdo->prepare("SELECT round(AVG(AssetUnderMgmt)) as aum FROM tblDetails GROUP BY City");
    $statement->execute();
    $results=$statement->fetchAll(PDO::FETCH_ASSOC);
    $json=json_encode($results);
    echo $json; <-- this is what I want to get, I'm getting it.
}
catch(PDOException $e) 
{
    echo "Error: " . $e->getMessage();
}
$pdo = null;
?>

现在,我想将结果存储在一个javascript变量中,为此我已经完成了以下代码。

<script type="text/javascript">
var jsonObj;
$.post( "assetsData.php", function(data) {  
    jsonObj = data;  <-- Here the data is coming fine.
}); 

上述警报打印的数据为

 [{"aum":"252"},{"aum":"250"},{"aum":"251"},{"aum":"248"},{"aum":"255"},{"aum":"250"},{"aum":"252"},{"aum":"250"},{"aum":"250"},{"aum":"250"},{"aum":"254"},{"aum":"252"},{"aum":"251"},{"aum":"246"},{"aum":"250"},{"aum":"255"},{"aum":"247"},{"aum":"253"},{"aum":"254"},{"aum":"257"},{"aum":"246"},{"aum":"250"},{"aum":"254"},{"aum":"249"},{"aum":"251"},{"aum":"248"},{"aum":"249"},{"aum":"253"},{"aum":"249"},{"aum":"251"},{"aum":"250"},{"aum":"249"},{"aum":"253"},{"aum":"253"}]

//First try
alert(jsonObj) <-- this gives undefined error.
// Second try
object = JSON.parse(jsonObj); 
var my_array = new Array(); 
for(var key in object ){ 
    my_array[key] = object[key]; 
}
alert(my_array); <--Gives: Uncaught SyntaxError: Unexpected token u
// third try
alert(jsonObj[0].aum); <-- Cannot read property '0' of undefined
// fourth try
alert(jsonObj['aum']); <-- Cannot read property 'aum' of undefined
 </script>

这是我想根据它的索引访问那些(json)值的地方。

FusionCharts.ready(function () {
    var salesByState = new FusionCharts({
        "type": "maps/maharashtra",
        "renderAt": "chartContainer",
        "width": "100%",
        "height": "700",
        "dataFormat": "json",
        "dataSource": {
            "chart": {
                "theme": "fint",
                    "caption": "Annual Assets (demo)",
                    "entityFillHoverColor": "#cccccc",
                    "numberPrefix": "Rs.",
                    "showLabels": "1",
                    "legendPosition": "BOTTOM"
            },
        //Defining color range for data range
        "colorrange": {
            "minvalue": "0",
                "startlabel": "Low",
                "endlabel": "High",
                "code": "e44a00",
                "gradient": "1",
                "color": [{
                "maxvalue": "30000",
                    "displayvalue": "Average",
                    "code": "f8bd19"
            }, {
                "maxvalue": "100000",
                    "code": "6baa01"
            }]
        },
       "data": [{
            "id": "IN.MH.AH",
                "value": obj[0].aum  <-- These are the places where I want to access the values inside the 'jsonObj'. Is this correct, if not then which is correct way?
        }, {
            "id": "IN.MH.AU",
                "value": obj[3].aum
        }, {
            "id": "IN.MH.YA",
                "value": "33038"
        }]
    }
});
salesByState.render();
});

试试这个代码:

var jsonObj;
$.post( "assetsData.php", function(data) {  
    jsonObj = data;
});

如果你的json喜欢这样:

[{"aum":"249"},{"aum":"253"},{"aum":"253"}]

你可以这样访问你的价值观:

jsonObj[0].aum

但是,请确保您的php代码生成如下json响应:

<?php 
    echo json_encode(array(myObj1, myObj2, myObj3));
?>

下面是一个来自jQuery.post()文档的示例:

示例:发布到test.php页面并获取以json格式(<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>)返回的内容。

$.post("test.php",{func:"getNameAndTime"},function(data){console.log(data.name);//约翰console.log(data.time);//下午2点},"json");

编辑:Ankit的命题:

var jsonObj;
$.ajax({
    type: 'POST',
    url: "assetsData.php",
    data: '',
    dataType: 'json',
    async: false,
    success: function(data) {
        jsonObj = data;
    }
});
alert(jsonObj[0].aum);