【问题标题】:Update DOM with jQuery ajax array results使用 jQuery ajax 数组结果更新 DOM
【发布时间】:2015-03-30 13:44:27
【问题描述】:

我有一个由第 3 方脚本生成的搜索结果,我想向其中添加数据。我已解析结果以获取 id 数组,并在数据库中查询其他字段。 ajax 成功方法接收格式化的数组,但现在我被困在如何将这些结果放入 DOM 中的正确位置。

HTML:

    <div class="ihf-results-property-info">
        <div class="ihf-results-price">LIST: $2,150,000</div>
        <div class="ihf-results-links"> <a href="#"> 24 Photos </a>
    </div>
    <div class="ihf-results-extra-info">
        <div class="ihf-results-listingnum hidden-xs">Listing # 727938</div>
    </div>
    Repeat...

我在示例中包含的最后一个 div 具有我用于查询的唯一 ID。我想用它来将 ajax 返回与 DOM 中的正确位置相关联。这是我的javascript:

jQuery(document).ready(function($) {

    //  grab the listings numbers so we can query the db for extra data
    var listings = $('.ihf-results-listingnum').map(function() {

        // grab just the digits
        var listingNum = $(this).text().replace(/[^0-9]/g, '');

        // add the listing number to the parent so we can target it later
        $( this ).parents('.ihf-results-extra-info').parent().addClass('marketing-details-' + listingNum);

        return listingNum;

    // use .get to create  an array of the listing numbers
    }).get();

    $.ajax({
        type: "GET",
        url: "custom/07-idx-queries.php",
        data: 'mlsNums=' + listings, // looks like ?mlsNums=735383,727468,699876...
        success: function(result) {
            // this logic came from here: http://stackoverflow.com/questions/15311320/how-to-work-with-jquery-ajax-and-php-array-return
            resultJson = $.parseJSON(result); 
            if (typeof resultJson == 'object') {
                jsObject = eval(resultJson);

                jsArray = [];
                for(elem in jsObject){
                    jsArray.push(jsObject[elem]);
                }
                console.log(jsArray);
                // this works as expected, except keys are 0 based

                // This is where it all falls apart. I want to extract each object and stick it in the DOM in the correct place
                jQuery.each(jsArray, function(key, value) {
                    $( this ).appendTo('.marketing-details-' + key);
                });
            }
            else {
                console.log("error occurred");
            }
        },
        error: function(xhr, status, error) {
            console.log(xhr.responseText);
        }
    })
});

我正在使用的 php 从 db 中产生所需的结果,但它是一个数字数组。我认为在尝试将结果放入 DOM 时,关联数组会更好地工作,这样我可以使用 ID 作为键并将它们与我添加的类匹配。以下是来自 custom/07-idx-queries.php 的相关代码:

$mls_nums = explode(",",$_GET['mlsNums']);
// removed all of the conditionals to keep the question clean
$html = array();

    foreach ($mls_nums as $mls_num) {
        // just retreiving a single object from each row for now
        $remarks = $mysqli->query("SELECT mr FROM listings WHERE ln = '$mls_num'")->fetch_object()->mr;

        // format the data
        $my_html = "<p class='marketing-remarks mlsnum-".$mls_num."'>$remarks</p>";

        // build an array of the results - necessary?
        array_push($html,$my_html);
    }

    // send the data back in a JSON string
    echo json_encode($html);

所以我的目标是查询数据库最多 10 行,并将结果插入到相同数量的新 div 中,这些新 div 是其类中具有相同 id 号的 div 的子级。我非常感谢任何帮助。

【问题讨论】:

  • 我认为您应该只粘贴与您的问题相关的最少代码。如果问题与 ajax 相关,请粘贴该部分。

标签: php jquery ajax


【解决方案1】:

在你的 PHP 中这样做:

$html[$mls_num] = $my_html;
// this isn't needed
// array_push($html,$my_html);

现在您返回的数据可以绑定到目标 div。

不清楚您是否可以控制示例第一部分中的 HTML,但这是一种方法。

<div class="ihf-results-listingnum hidden-xs">Listing # 727938</div>
<div class="remarks" id="remarks_<?= $listingid; ?>"></div>

然后在 JavaScript $("#remarks_" + key).html(value);

否则,您需要使用 jQuery 使用 :contains 选择器来定位具有列表 ID 的 div:

$("div:contains('# " + key + "')").appendTo(value);

'# " + key + "' 将等同于 # 1234 或其他任何内容。但是,如果同一列表在页面上出现两次,这将不起作用!

【讨论】:

  • 在更改我的 php 代码以匹配您的示例并在我的 jQuery.each() 函数中添加 console.log(key + ": : + value); 后,我仍然看到数字键(从零开始)。知道我做错了什么吗?
  • 糟糕... jQuery 的每个函数都是function( index, value ),所以尝试执行console.log(value) 看看会显示什么。
  • 我也试过了,结果一样。我认为 jsArray 转换可能是不必要的。我刚刚在 .each 循环中用 jsObject 替换了 jsArray,现在 6 位键出现了。我现在正在排除故障。
【解决方案2】:

好的,下面是工作成功的方法。感谢 LG_PDX 清理了 php。我消除了不必要的处理,因为.each() 似乎可以很好地遍历 JSON 响应:

            success: function(result) {
            resultJson = $.parseJSON(result);
            if (typeof resultJson == 'object') {

                $.each(resultJson, function(key, value) {
                    $('.marketing-details-' + key).append( value );
                });
            }
        },
        error: function(xhr, status, error) {
            console.log(xhr.responseText);
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-18
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    相关资源
    最近更新 更多