簡體   English   中英

數組保持為空 AJAX/JS/PHP

[英]Array remains empty AJAX/JS/PHP

我的 php 腳本以 json 格式返回響應:

echo json_encode(array(
    "Subject"=>$row['Subject'],
    "date"=>$row['Date'],
    "Sender"=>$row['username'],
    "sender_id"=>$row['user_id'],
    "Message"=>$row['Message'])
);

在 JS 中,單列應該被推送到不同的數組中以供以后用於表,但它們仍然是空

我認為這個問題與異步有關,但我不知道該怎么做。

這是JS代碼。

var id =45678;

 var names = [];
    var subjects = [];
    var dates = [];
    var messages = [];
    var sender_ids = [];

function getData() {

    return $.ajax({
     type: "post",
     url: '',
     data: {user: id},
     dataType: 'json',
     success: function(response){

        $.each(response, function(i, row) {

         names.push(response.Sender);
         subjects.push(response.Subject);
         dates.push(response.date);
         sender_ids.push(response.sender_id);
        })
     }
    });
  }

$(document).ready( function() {

    getData().done(function (response) {

        if(response.Sender != null) {

            for (var i in response.Sender){
                names.push(response.Sender[i]);

                alert(names); 
            }
        }
        alert(names);
    });

});

問題是您返回了錯誤的 ajax 變量,return 語句必須在成功函數中,並且在完整函數中,以便您有一個后備。 不幸的是, .done 部分沒有(響應)參數。 要么您將在成功功能中完成所有工作,要么您將從那里返回所有內容。

var id =45678;

function getData(obj) {

    return ({
     type: "post",
     url: '',
     data: {user: id},
     dataType: 'json',
     success: function(response){
        obj.names.push(response.Sender);
        obj.subjects.push(response.Subject);
        obj.dates.push(response.date);
        obj.messages.push(response.Message);
        obj.sender_ids.push(response.sender_id);
        return obj;
     },
     complete: function(){
       return obj;
     }
    });
  }

$(document).ready( function() {
    var obj = {}
    obj.names = [];
    obj.subjects = [];
    obj.dates = [];
    obj.messages = [];
    obj.sender_ids = [];

    obj = getData(obj);

});

嘗試這個。 我希望這可以幫助你。

暫無
暫無

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

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