简体   繁体   English

如何使用JQuery获得PHP数组结果

[英]How to get PHP array results using JQuery

Below are a couple of queries that ultimately build an array. 下面是几个最终构成数组的查询。

if(isset($_POST['getarray'])){
    try{
        $ret = array();
        $stmt = $db->prepare('SELECT groupdate, groupid
                                    FROM participationtemp
                                    WHERE memberid = :memberid
                                    AND groupid = :groupid
                                    ORDER BY groupdate, groupid DESC');
        $stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
        $stmt->bindValue(':memberid', $_SESSION['memberid'], PDO::PARAM_INT);
        $stmt->execute();
        $result = $stmt->fetchAll();
        foreach($result as $row){
            $attenddate = $row[0];
            $stmt = $db->prepare('SELECT h.clientid, attend, attend_date
                                        FROM history AS h 
                                        INNER JOIN suspended AS s on s.clientid = h.clientid                                    
                                        WHERE h.memberid = :memberid  
                                        AND h.groupid = :groupid
                                        AND attend_date = :attenddate
                                        AND suspend = "N"');
            $stmt->bindValue(':memberid', $_SESSION["memberid"], PDO::PARAM_INT);
            $stmt->bindValue(':groupid', $_POST['groupid'], PDO::PARAM_INT);
            $stmt->bindValue(':attenddate', $attenddate, PDO::PARAM_STR);
            $stmt->execute();
            $result = $stmt->fetchAll();
            foreach($result as $row ) {
                array_push($ret, ['id' => $row[0], 'gdate' => $row[2]]);
            }
        }
        echo json_encode($ret);
        exit();
    } catch (PDOException $ex){
            mail_error($ex);
    }
}

After returning to JQuery, alert(re); 返回JQuery之后, alert(re); shows I successfully created the array. 显示我成功创建了数组。

success:function(re){
    alert(re);

在此处输入图片说明

But I'm having trouble accessing the array data. 但是我在访问数组数据时遇到了麻烦。 Without success, this is what i've tried: 没有成功,这就是我尝试过的:

data = $.parseJSON(re);

$.each(data, function(i, val) {
    alert(i + "=" + val);
});

and this: 和这个:

data = $.parseJSON(re);

$.each(data, function(i, val) {
    if(i == "id"){
        alert(i + "=" + val);
    }
    if(i == "gdate"){
        alert(i + "=" + val);
    }
});

I've also tried dot notation . 我也尝试过dot notation

$.each(re.id, function(i, val) {
    alert(i + "=" + val);
    }
});
$.each(re.gdate, function(i, val) {                             
    alert(i + "=" + val);                               
});

I've never used JSON before and don't understand why I can't retrieve the array data. 我以前从未使用过JSON,也不了解为什么我无法检索数组数据。 Any help will be appreciated. 任何帮助将不胜感激。 Thanks. 谢谢。

The following code checks whether re is a string, or an object. 以下代码检查re是字符串还是对象。 The latter is possible if jQuery.ajax() method is used with "json" dataType . 如果jQuery.ajax()方法与“ json” dataType一起使用,则后者是可能的。 Also, jQuery is capable of parsing JSON automatically, if the response MIME type is application/json (the Content-Type HTTP header), particularly. 另外,如果响应的MIME类型是application/jsonContent-Type HTTP标头),则jQuery能够自动解析JSON。 So it is a good idea to check if re has been parsed by jQuery. 因此,检查re是否已由jQuery解析是一个好主意。

var d = typeof re === 'string' ? JSON.parse(re)  : re;
var i;

for (i = 0; i < d.length; i++) {
  console.log("id = ", d[i].id,
              "gdate = ", d[i].gdate);
}

I'd recommend returning the appropriate content type from PHP: 我建议从PHP返回适当的内容类型:

    header ('Content-Type: application/json');
    echo json_encode($ret);
    exit();
$.each(re, function(i, val) {
    alert(val.id + "=" + val.gdate);
});

Try this code :) 试试这个代码:)

 // Json in string format var jsonString = '[{"id":"1", "gdate":"2016-10-13"},{"id":"2", "gdate":"2016-10-13"},{"id":"3", "gdate":"2016-10-13"},{"id":"4", "gdate":"2016-10-13"},{"id":"5", "gdate":"2016-10-13"},{"id":"6", "gdate":"2016-10-13"}]'; // Convert string to json object var json = JSON.parse(jsonString); // Iterate over json object jQuery.each(json, function(index, value) { console.log(index, value); }); // Simple access to attribute in json object console.log('json[1][\\'id\\'] = ', json[1]['id']); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

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

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