【问题标题】:Convert the String to JSON, getting by JQuery.Ajax将字符串转换为 JSON,通过 JQuery.Ajax 获取
【发布时间】:2013-01-04 16:40:41
【问题描述】:

我的 php 代码通过此链接 getPower.php?year=2012&country=tr 产生类似的东西

"Kasan":[[1,50]]
"Tasan":[[1,51],[2,52],[3,52]]
"Hasan":[[1,50]]
"Masan":[[1,51],[2,52],[3,52]]

使用此代码;

$row = $result->fetch_assoc();

echo json_encode($row['teamName']). ":" ;

putPowerbyTeam($db,$row['teamID'],$year); //End with echo "json_encode($returnArray);"  

echo "\n";

我正在准备用这段代码将它们转换成 JavaScript 对象;

$.ajax({type: "GET",
url: "getPower.php",
data: {year : "year", country : "country"},
success: function(JSONText) {

    var lines = JSONText.split('\n');

    $.each(lines,function(lineNo,line)
                    {
        var mainItems = line.split(':');
        chart.series[lineNo].name = jQuery.parseJSON(eval(mainItems[0]));
        chart.series[lineNo].setData(jQuery.parseJSON(eval(mainItems[1])), true);
    });

},
error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    alert(thrownError);
}

我是一个错误,说不能拆分空值。所以,返回 null 但我不能确定这个 javascrip 代码的任何部分。

那么,为什么会返回 null 呢? 我能做些什么? 其他的好吗?

【问题讨论】:

  • 您的 JSON 是否有效?粘贴输出here

标签: php javascript ajax json split


【解决方案1】:

你可以像这样使用dataType

$.ajax({type: "GET",
url: "getPower.php",
data: {year : "year", country : "country"},
dataType: 'json',
success: function(JSONText) {

// do something

【讨论】:

    【解决方案2】:

    不要尝试使用多个 echojson_encode 构建您的 JSON。使用一个大的关联数组,然后使用echo json_encode(array)

    类似这样的:

    $array = array();
    
    $teamName = $row['teamName'];
    
    $array[$teamName] = putPowerbyTeam($db,$row['teamID'],$year); // Return the array instead of doing json_encode($returnArray);
    
    echo json_encode(array);
    

    【讨论】:

    • 如果我用数组获取所有数据,“chart.series[lineNo].setData”有问题,它只需要数据,我应该将名称和数据分开。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 2012-10-06
    • 1970-01-01
    相关资源
    最近更新 更多