简体   繁体   English

通过JQuery.Ajax将字符串转换为JSON

[英]Convert the String to JSON, getting by JQuery.Ajax

My php code produce something like that with this link getPower.php?year=2012&country=tr 我的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]]

With this code; 有了这个代码;

$row = $result->fetch_assoc();

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

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

echo "\n";

And I'm trayin to convert them into JavaScript Object with this code; 我用这个代码将它们转换为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);
}

I'm an error which say cannot split the null. 我错了,说不能拆分null。 So, null is returned but i can't be sure any part of this javascrip code. 因此,返回null,但是我不确定此javascrip代码的任何部分。

So, why null is returned? 那么,为什么返回null? What can i do? 我能做什么? Is the rest is good? 其余的好吗?

You can use dataType like this : 您可以像这样使用dataType

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

// do something

Don't try to build your JSON with multiple echo and json_encode . 不要尝试使用多个echojson_encode构建JSON。 Use one big associative array and then echo json_encode(array) . 使用一个大的关联数组,然后echo json_encode(array)

Something like this : 像这样的东西:

$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM