繁体   English   中英

JSON将对象解析为javascript函数:syntaxerror

[英]JSON parsed object into a javascript function : syntaxerror

我正在解析从我的数据库通过ajax查询的json脚本。 我想在javascript函数“ addComp()”中使用查询的内容(以json格式),该功能为地图上的每个建筑物添加了一个几何成分。 这是jQuery / ajax代码:

$.ajax({ 

        type: "GET",
        url: "ajax_processor.php",
        dataType : "json",

        success:function(data){ 
        console.log(data); //here I got what i want

        var geometryElement = $.parseJSON(data);

                for (var i=0; i<geometryElement.length; i++) {
                      addComp(  geometryElement[i].bldg, 
                                    geometryElement[i].iZ, 
                                    geometryElement[i].iType,
                                    geometryElement[i].x0,
                                    geometryElement[i].y0,
                                    geometryElement[i].p, ...); //parameters p1, p2, p3, p4, p5
                 }
        }
});

通过PHP查询的JSON脚本为:

{"ID_geometryElement":"1","bldg":"1","iZ":"1","iType":"1","x0":"23","y0":"5","p1":"5","p2":"2","p3":"3","p4":"0","p5":"0"},
{"ID_geometryElement":"2","bldg":"1","iZ":"1","iType":"1","x0":"24","y0":"7","p1":"2.5","p2":"4","p3":"3.5","p4":"0","p5":"0"},
 ...

但这在地图上没有显示任何内容,并且出现以下错误:

 Uncaught SyntaxError: Unexpected token o          jquery.js:550
 jQuery.extend.parseJSON                           jquery.js:550    
 $.ajax.success                                    index_LF.php:3725
 fire                                              jquery.js:3074
 self.fireWith                                     jquery.js:3186
 done                                              jquery.js:8253
 callback                                          jquery.js:8796
 handleStateChange                                 firebug-lite.js:18917 

有谁知道它来自哪里以及如何修复?

编辑:在PHP方面,我得到了:

    <?php

    $host = 'localhost';
    $databaseName = 'localdb';
    $tableName = 'building_geometry';
    $user = 'admin';
    $password = 'password';


    $connexion = mysql_connect($host,$user,$password);
    $dbs = mysql_select_db($databaseName, $connexion);

    $sql = mysql_query('SELECT * from building_geometry');

    $rows = array();
    while($r = mysql_fetch_assoc($sql)) {
        $rows[] = $r;
    }

    echo json_encode($rows);

    ?>

但是问题不在php中,我解析了json中已经存在的内容的两倍(dataType是json)。

那是无效的JSON。 它看起来像数组文字,但是缺少外部方括号。

那是,

{"foo": 0, ... },
{"bar": 1, ... },

是无效的,但如果是

[{"foo": 0, ... },
{"bar": 1, ... }]

无论如何,如果您要告诉jQuery数据类型是JSON,而实际上 JSON,则不必解析它。 “ data”参数将是已解析的对象,而不是未解析的字符串。

暂无
暂无

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

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