【问题标题】:Array not sent all element, only get 1st one数组未发送所有元素,仅获得第一个
【发布时间】:2015-03-02 10:40:46
【问题描述】:

我想在 15 秒间隔后从当前页面获取所有帖子 ID 以进行服务器端 php 查询。 PHP 查询将在 Sql 中找到匹配的 id,如果找到特定 id 的任何数据,它将是 .append 它。

所以在我当前的页面中有很多带有自己动态帖子 ID 的 div,例如:

<div class="case" data-post-id="111"></div>

<div class="case" data-post-id="222"></div>

<div class="case" data-post-id="333"></div>

<div class="case" data-post-id="anything else dynamic no"></div>

我想要,我的 javascript 将获取此 ID 并将其发送到 php 查询,以便在 Sql 中查找任何匹配项。

我的array 在这里只有第一个帖子 ID。问题是我的 javascript 数组或 php 数组

我的更新脚本:(这里var CID无法获取id,只能获取第一个id)

//make array to get id
var CID = []; //get dynamic id 
$('div[data-post-id]').each(function (i) {
    CID[i] = $(this).data('post-id');
});

function addrep(type, msg) {
    CID.forEach(function (id) {
        $("#newreply" + id).append("");
    });
}
var tutid = '<?php echo $tutid; ?>';

function waitForRep() {
    $.ajax({
        type: "GET",
        url: "/server.php",
        cache: false,
        data: {
            tutid: tutid,
            // this way array containing all ID's can be sent:
            cid: CID
        },
        timeout: 15000,
        success: function (data) {
            addrep("postreply", data);
            setTimeout(
            waitForRep,
            15000);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            setTimeout(
            waitForRep,
            15000);
        }
    });
}

server.php

if($_REQUEST['tutid'] && $_REQUEST['cid']){
    //make array to cid to get id
    foreach($_REQUEST['cid'] as $key => $value){

       $res = mysqli_query($dbh,"SELECT * FROM test WHERE id =".$value." AND page_id=".$_REQUEST['tutid']." ORDER BY id DESC LIMIT 1") or die(mysqli_error($dbh));

        $rows =  mysqli_fetch_assoc($res);  

        $row[] = array_map('utf8_encode', $rows); //line 80
        $data = array();

        $data['id'] = $rows['id']; 
        //etc all

            //do something

if (!empty($data)) {
    echo json_encode($data);
    flush();
    exit(0);
}
} }

【问题讨论】:

  • 数组已正确构建:jsfiddle.net/k5mo22Lc,尽管您可以使用 map() 缩短它。您是否检查过服务器正在检索哪些数据?
  • 如何检查,先生。我的 php 数组在 server.php 文件中是否正常?
  • 在您的 php 文件中,执行 print_r($_REQUEST['cid']);出口; -> 这打印什么?
  • 是的,你的 server.php 文件有问题。你在循环中回显,第一次迭代后,退出语句停止脚本
  • @koc 请查看我之前的评论

标签: javascript php jquery arrays


【解决方案1】:

更改小代码并检查一下

//make array to get id
var CID = []; //get dynamic id 
$('div[data-post-id]').each(function (i) {
    CID[CID.length] = $(this).data('post-id');
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-20
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多