【问题标题】:parse JSON object passed through Ajax解析通过 Ajax 传递的 JSON 对象
【发布时间】:2012-12-11 17:12:17
【问题描述】:

我正在尝试解析从数据库返回并编码为 JSON 对象的信息。

这是检索信息的代码:

   private function retrieve_standards_one(){
    $dbh = $this->connect();
    $stmt = $dbh->prepare("SELECT code, standard_one_id 
                           FROM standard_one 
                           WHERE grade_id = :grade_id 
                           ORDER BY standard_one_id");
    $stnd = array();
    for($x = 0; $x < (count($this->grades)); $x++){                    
    $stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
    $stmt->execute();
    $stnd[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    $json = json_encode($stnd);
    return $json;
}

以及我尝试解析信息的方式:

  $.ajax({
        type: "POST",
        url: "lib/search/search.standards_one.php",
        async: "false",
        data: {subjects: subjects, grades: grades},
        success: function(response){
                $("#standards_results").html("");
                var obj = $.parseJSON(response);
                $.each(obj, function(){
                    alert(this['code'] + ", " + this['standard_one_id'])
                });
            }
        });

我尝试了许多不同的方法来做到这一点,但我只得到 [object][object] 作为响应。

这是回复:

http://i.imgur.com/E5Hux.png

【问题讨论】:

  • [object Object] 是对象的默认字符串表示形式,因此您的代码可能工作正常。 alert 是一个非常糟糕的调试工具,如果您想检查变量,请改用console.log。并且不要用字符串连接对象!
  • consol.log 仍然只返回 [objects]s
  • 您是否删除了字符串连接?做console.log(this['code']); console.log(this['standard_one_id'])alert 和字符串连接都会将对象转换为字符串,这是您应该避免的。
  • 是的,我跑了:consol.log(this['code'], this['standard_id']);
  • dataType:'json' 添加到$.ajax 选项,jQuery 将自动管理 JSON 解析。 response 将是数组或对象,具体取决于从服务器发送的内容。不要使用async:false

标签: javascript jquery ajax json pdo


【解决方案1】:

将 dataType 属性添加到您的 AJAX 调用中。

$.ajax ({

    type: "POST",
    dataType: "JSON",
    url: "lib/search/search.standards_one.php",
    async: "false",
    data: {subjects: subjects, grades: grades},
    success: function(response){
            $("#standards_results").html("");
            var obj = $.parseJSON(response);
            $.each(obj, function(){
                alert(this['code'] + ", " + this['standard_one_id'])
            });
        }
    });

【讨论】:

  • 如果你这样做,你必须删除$.parseJSON(response);。此外,我认为这不会有什么不同。您只需更改解析响应的时刻。
【解决方案2】:

使用

console.log(this['code'] , this['standard_one_id'])

而不是

alert(this['code'] + ", " + this['standard_one_id'])

【讨论】:

  • 应该是console.log(this['code'], this['standard_one_id'])。如果你保持字符串连接,它不会有太大的不同。
  • 是的,它可以提供更好的输出
  • consol.log 仍然只返回 [objects]s
  • 您是否尝试记录您的 ajax 响应
  • 也可以在您的问题中发布回复吗?
猜你喜欢
  • 1970-01-01
  • 2017-03-02
  • 2015-07-06
  • 2021-09-21
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多