得到一个“syntaxError:JSON。当在x列x列中加入一个0到个位数字时,将会出现“,”或“。”

时间:2021-03-06 22:08:30

i am using dataTables to display data from a MySQL database by using PHP, Ajax, and jQuery. The data i am showing are numbers and everything works fine.

我使用dataTables从MySQL数据库中使用PHP、Ajax和jQuery显示数据。我展示的数据都是数字,一切正常。

Here is my php script

这是我的php脚本。

require_once '../core/init4ajax.php';
$loteria=$_POST['loteria'];

$lotto = new Lotto();

$ultimos_resultados=$lotto->last_results($loteria,20);

function objectToArray($d) 
{
    if (is_object($d)) {
        // Gets the properties of the given object
        // with get_object_vars function
        $d = get_object_vars($d);
    }

    if (is_array($d)) {
        return array_map(__FUNCTION__, $d);
    } else {
        // Return array
        return $d;
    }
}

$new_array = objectToArray($ultimos_resultados);

$result = array();
echo '[';
foreach ($new_array as $new_array2) {
    echo '[';
    foreach ($new_array2 AS $value){
    /********The following piece of code is used to add a leading zero to single digit numbers********/
    /*if (1 == strlen($value)) {
        $zero=0;
        $value = $zero.$value;
    }*/
        echo $value;
        if($value!==end($new_array2)){ //referencias: http://*.com/a/8780881/1883256
            echo',';
        }
    }
    echo ']';//referencias: http://www.mydigitallife.info/how-to-access-php-array-and-multidimensional-nested-arrays-code-syntax/
    if($new_array2!==end($new_array)){
        echo ',';
    }else{ echo '';}
}
echo ']';

Here is the output sample of the php script:

下面是php脚本的输出示例:

[[2740,3,9,21,27,46,48],[2741,3,4,13,22,27,29], ... ,[2757,32,34,35,36,50,55]]

And here is the ajax code.

这是ajax代码。

$(document).ready(function() {

$.ajax({
    url: "ajax/default_chart_numbers_table.php",
    type: "post",
    data: {loteria: 'melate'},
    success : function (resp){
        // would look something like ['val1','val2', 'etc']
        var column_data = $.parseJSON(resp);
        //alert(column_data);
        // adding data to datatables
        for (var j=0;j<=column_data.length-1;j++){
            // adding each row with its column data
            //iterating values to add leading zeros to single digits:

            $('#dataTables-melate').dataTable().fnAddData(column_data[j]);
        }
    },
    error: function(jqXHR, textStatus, ex) {
      console.log(textStatus + "," + ex + "," + jqXHR.responseText);
    }
});    


} );

I have realized that i want the single digit numbers to be lead by a zero, e.g. 4, should be shown as 04.

我已经意识到我想要一个零的个位数,例如4,应该显示为04。

By adding the code in order to add a leading zero (this piece of code is already in my php code but commented):

通过添加代码来添加一个前导零(这段代码已经在我的php代码中,但是注释了):

if (1 == strlen($value)) {
            $zero=0;
            $value = $zero.$value;
        }

Now the php code returns the array the way i want it:

现在php代码以我想要的方式返回数组:

[[2740,03,09,21,27,46,48],[2741,03,04,13,22,27,29], ... ,[2757,32,34,35,36,50,55]]

however, now from the ajax script i get the following error:

但是,现在从ajax脚本中我得到了以下错误:

SyntaxError: JSON.parse: expected ',' or ']' after array element at line 1 column 9 of the JSON data

SyntaxError:JSON。解析:在JSON数据的第1行第9列的数组元素后,期望“,”或“]”。

and the data is no longer displayed in the dataTables.

数据不再显示在dataTables中。

Why is this happening? How can i fix it?

为什么会这样?我怎样才能修好它?

I HAVE FIXED IT: I just had to add double quotes to those single edit numbers:

我已经修复了:我只需要添加双引号到那些单个编辑数字:

if (1 == strlen($value)) {
    $zero=0;
    $value = '"'.$zero.$value.'"';
}

And that did the trick! ☺

这就够了!☺

2 个解决方案

#1


1  

It has nothing to do with the leading zeros. This is because you treat the output as JSON, which it is not. It is an array of arrays. The error is caused by the line :

它与前导零无关。这是因为您将输出视为JSON,而它不是。它是数组的数组。错误是由线路引起的:

var column_data = $.parseJSON(resp);

Try test the output / supposed JSON with http://jsonlint.com. Example how it could work :

尝试使用http://jsonlint.com测试输出/假设的JSON。举例说明它是如何工作的:

var column_data = [
     [2740,3,9,21,27,46,48],
     [2741,3,4,13,22,27,29],
     [2757,32,34,35,36,50,55]
];

var dataTable = $('#dataTables-melate').dataTable()

for (var j=0;j<=column_data.length-1;j++){
  // adding each row with its column data
  //iterating values to add leading zeros to single digits:
  dataTable.fnAddData(column_data[j]);
}

see demo -> http://jsfiddle.net/jPLSf/

看到演示- > http://jsfiddle.net/jPLSf/

#2


1  

Adding a leading zero changes a javascript "number" to a "string". So JSON.parse returns an error expecting numbers (eg: 4) but instead sees a string (eg: "04").

添加一个前导零将一个javascript“数字”更改为“字符串”。因此,JSON。解析返回一个期望数字(如:4)的错误,但是却看到一个字符串(例如:“04”)。

In the picture below, you can see that I have ran two commands that try to parse a string into JSON. In the first command, the second item in the first array is 03 and outputs a SyntaxError. In the second command, The 03 was changed to 3 and now it parses properly.

在下面的图中,您可以看到我已经运行了两个命令,它们试图将一个字符串解析为JSON。在第一个命令中,第一个数组中的第二个项是03,并输出一个SyntaxError。在第二个命令中,03被改为3,现在它正确地解析了。

得到一个“syntaxError:JSON。当在x列x列中加入一个0到个位数字时,将会出现“,”或“。”

I would recommend researching how to add data to the datatable without leading zeros in order for the table to show up properly and then change how the numbers are viewed/displayed

我将建议研究如何在没有前导零的情况下向datatable中添加数据,以使表正确显示,然后更改查看/显示数据的方式。

I would also recommend researching json_encode() to echo json from PHP.

我还建议研究json_encode()以从PHP返回json。

I use json_encode() to echo json from PHP all the time to make sure I get the proper data output when making AJAX calls.

我一直使用json_encode()从PHP返回json,以确保在进行AJAX调用时得到正确的数据输出。

#1


1  

It has nothing to do with the leading zeros. This is because you treat the output as JSON, which it is not. It is an array of arrays. The error is caused by the line :

它与前导零无关。这是因为您将输出视为JSON,而它不是。它是数组的数组。错误是由线路引起的:

var column_data = $.parseJSON(resp);

Try test the output / supposed JSON with http://jsonlint.com. Example how it could work :

尝试使用http://jsonlint.com测试输出/假设的JSON。举例说明它是如何工作的:

var column_data = [
     [2740,3,9,21,27,46,48],
     [2741,3,4,13,22,27,29],
     [2757,32,34,35,36,50,55]
];

var dataTable = $('#dataTables-melate').dataTable()

for (var j=0;j<=column_data.length-1;j++){
  // adding each row with its column data
  //iterating values to add leading zeros to single digits:
  dataTable.fnAddData(column_data[j]);
}

see demo -> http://jsfiddle.net/jPLSf/

看到演示- > http://jsfiddle.net/jPLSf/

#2


1  

Adding a leading zero changes a javascript "number" to a "string". So JSON.parse returns an error expecting numbers (eg: 4) but instead sees a string (eg: "04").

添加一个前导零将一个javascript“数字”更改为“字符串”。因此,JSON。解析返回一个期望数字(如:4)的错误,但是却看到一个字符串(例如:“04”)。

In the picture below, you can see that I have ran two commands that try to parse a string into JSON. In the first command, the second item in the first array is 03 and outputs a SyntaxError. In the second command, The 03 was changed to 3 and now it parses properly.

在下面的图中,您可以看到我已经运行了两个命令,它们试图将一个字符串解析为JSON。在第一个命令中,第一个数组中的第二个项是03,并输出一个SyntaxError。在第二个命令中,03被改为3,现在它正确地解析了。

得到一个“syntaxError:JSON。当在x列x列中加入一个0到个位数字时,将会出现“,”或“。”

I would recommend researching how to add data to the datatable without leading zeros in order for the table to show up properly and then change how the numbers are viewed/displayed

我将建议研究如何在没有前导零的情况下向datatable中添加数据,以使表正确显示,然后更改查看/显示数据的方式。

I would also recommend researching json_encode() to echo json from PHP.

我还建议研究json_encode()以从PHP返回json。

I use json_encode() to echo json from PHP all the time to make sure I get the proper data output when making AJAX calls.

我一直使用json_encode()从PHP返回json,以确保在进行AJAX调用时得到正确的数据输出。