首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在ajax js中显示数组对象php?

问如何在ajax js中显示数组对象php?
EN

Stack Overflow用户
提问于 2017-06-11 14:31:53
回答 2查看 771关注 0票数 0

我有一个函数,使用mysql从php返回数组对象,我想使用javascript从ajax函数调用数组,但我不知道如何在javascript动态表或控制台日志中显示数组对象php。

我的php文件:

代码语言:javascript
复制
$age = $_POST["param"];  //value ajax param
$list = BussinesLayer::getUsers($age);  //load my list

//list properties ej:  list->getName(), getAge(), getOcupation()->getDescription(), etc..

echo json_encode($list); 

我的js函数:

代码语言:javascript
复制
 fnListUsers: function() {

    var agedata = $("#txtAge").val();

    $.ajax({
        type        : "POST",
        url         : "../ControllerFile/SearchUsers.php",
        data        : {"param" : agedata},
        dataType    : 'json',
        success     : global.fnSuccessList,
        error       : function (XMLHttpRequest, textStatus, errorThrown) {
                            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                      }
    });

},
fnSuccessList: function(data) {
    var array = JSON.parse(data); // -> dont work  Uncaught SyntaxError: Unexpected token o in JSON at position 1
    var array2 = jQuery.parseJSON(data);  // dont work  Uncaught SyntaxError: Unexpected token < in JSON at position 0

    //how display my arrayobject ?
    console.log(data.getName, data.getOcupation.getDescripition);

}
EN

回答 2

Stack Overflow用户

发布于 2017-06-11 15:39:11

您的成功函数已经有了json格式的data。因此您不需要在JSON中再次解析它。只需使用console.log(data)查看您的对象即可。

代码语言:javascript
复制
fnSuccessList: function(data) {
    var array = JSON.parse(data); // remove this
    var array2 = jQuery.parseJSON(data);  // remove this

    console.log(data);

}
票数 1
EN

Stack Overflow用户

发布于 2017-06-11 15:48:21

这里您做错了,您使用了已经解析数据的dataType : 'json',但在此之后,您再次尝试解析。这会导致错误。

代码语言:javascript
复制
fnListUsers: function() {

    var agedata = $("#txtAge").val();

    $.ajax({
        type        : "POST",
        url         : "../ControllerFile/SearchUsers.php",
        data        : {"param" : agedata},
        dataType    : 'JSON',
        success     : global.fnSuccessList,
        error       : function (XMLHttpRequest, textStatus, errorThrown) {
                            alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
                      }
    });

},
fnSuccessList: function(data) {

    // this will show your data
    console.log(data); 

    /* Don't use this just access data directly 
     var array = JSON.parse(data); // -> dont work  Uncaught SyntaxError: Unexpected token o in JSON at position 1
    var array2 = jQuery.parseJSON(data);  // dont work  Uncaught SyntaxError: Unexpected token < in JSON at position 0
   */


}

在控制台中查看,如果您的数据如下所示,则它已被解析

​

如果看起来像这样,那么它就不会被解析

​

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44481030

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档