簡體   English   中英

AJAX僅返回最后一個數組項

[英]AJAX returns only last array item

我想創建一個異步AJAX查詢來在網頁加載完成時檢查服務器狀態。 不幸的是,當涉及到來自已處理PHP的數據顯示時,我只收到一個值。

JS:

<script>

  window.onload = function() {
      test();
    };

  function test()
  {
      var h = [];

      $(".hash td").each(function(){

        var hash = $(this).closest('#h').text();

        if (hash) {
            $.ajax({
                url: 'stat.php',
                method: 'POST',
                async: true,
                data: {hs: JSON.stringify(hash)},
                success: function(data) {
                    $('.result').replaceWith(data);
                }
            });
        }
      });
    }
</script>

PHP:

<?php

require_once ('inc/config.php');
require_once ('inc/libs/functions.php');

if (isset($_POST['hs'])) {

  $hash = json_decode($_POST['hs']);

  serverstatus($hash);
}

function serverstatus($hash) {

    $address = DB::queryFirstRow("SELECT address,hash FROM servers WHERE hash=%s", $hash);

    $address_exploded = explode(":", $address['address']);
    $ip = $address_exploded[0];
    $port = $address_exploded[1];

    $status = isServerOnline($ip,$port);

    if ($status) {
      $s = "Online $ip";
    } else {
      $s = "Offline";
    }
    echo $s;
}

?>

我將PHP的結果嵌入到表行中。 我看到AJAX遍歷數組,但是所有行都收到相同的值(數組中最后檢查的元素)。

$('.result')所有元素與類result匹配。 然后, replaceWith將用您提供的內容替換它們中的每一個。

如果只想影響某個結構(也許是同一行?)中的.result元素,則需要使用find或類似方法:

function test()
{
    var h = [];

    $(".hash td").each(function(){
        var td = $(this);                              // <====
        var hash = td.closest('#h').text();
        var result = td.closest("tr").find(".result"); // <====

        if (hash) {
            $.ajax({
                url: 'stat.php',
                method: 'POST',
                async: true,
                data: {hs: JSON.stringify(hash)},
                success: function(data) {
                    result.replaceWith(data);          // <====
                }
            });
        }
    });
}

顯然

var result = td.closest("tr").find(".result"); // <====

...將需要進行調整以使其成為您真正想要的樣子,但這就是想法。


您問題中的這一行建議使用反模式:

var hash = $(this).closest('#h').text();

id值在文檔中必須是唯一的,因此您永遠不需要找到與任何給定元素“最接近”的一個。 如果DOM中有多個id="h"元素,請將其更改為使用classdata-*屬性。

謝謝大家的幫助。 我的最后一個,顯然很臟但是可以正常工作的代碼:

function testServerPage()
{
    var h = [];

    $(".hash li").each(function(){

      var hash = $(this).closest('#h').text();

      if (hash) {
          $.ajax({
              url: 'stat.php',
              method: 'POST',
              //async: true,
              data: {hs: JSON.stringify(hash)},
              success: function(data) {
                  $('#' + hash).replaceWith(data);
              }
          });
      }
    });
    return false;
}

我剛剛向元素添加了動態變量:

success: function(data) {
                      $('#' + hash).replaceWith(data);
                  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM