将ajax的值存储到javascript变量中

时间:2015-02-12 10:36:52

标签: javascript php jquery ajax

我有一个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();
});

1 个答案:

答案 0 :(得分:0)

试试这段代码:

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 ); // John
         console.log( data.time ); // 2pm
    }, "json");

修改 来自Ankit的提案:

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