简体   繁体   English

准备SQL-AJAX返回数据

[英]Prepare SQL - AJAX return Data

I need some help setting up DB marker retrieval. 我需要一些帮助来设置数据库标记检索。 I got a bit confused on what exactly to pass back. 我对到底传回的内容有些困惑。 Here is what I have so far: 这是我到目前为止的内容:

data returned: 返回的数据:

["Chatswood NSW AU","Chippendale NSW AU"]

JS: JS:

var opdata = [];
    function markers() {
            $.post("id.php", {id: <?php echo $id; ?>})
            .done(function(data) {
                //data is array returned
                opdata = data; //Tried this
                $(opdata) = data; //Tried this
                opdata.push(data); //Tried this
                $.each(data, function(i) { //Tried this
                    opdata.push(data[i]);
                });
            });
            console.log(opdata); //Shows [] empty array regardless what i do
        }

PHP: PHP:

$arr = array();
while (  $selectData -> fetch() ) {
    $arr[] = $address;
}
echo json_encode($arr);

How do I go about retrieving data? 如何获取数据? None of the above is working. 以上都不起作用。

This is driving me nuts.. should i just $.ajax instead? 这让我发疯..我应该只是$ .ajax吗?

The call to .done is asynchronous, meaning that .done finishes right away, BEFORE the ajax call is made, and console.log is called right after, even if the http call is not finished yet. .done的调用是异步的,这意味着.done完成,即.done ajax调用之前,然后立即调用console.log (即使http调用尚未完成)。

Based on your use case and context you can choose between 3 options to return opdata back to the caller function: 根据您的用例和上下文,您可以在3个选项之间进行选择,以将opdata返回给调用者函数:

///// OPTION 1: synchronous call
function markersUsingSynchronousCallToAjax() {
    var opdata = [];
    $.ajax({
        type: "POST",
        url: "id.php",
        async: false, // disable asynchronous call to ajax
        data: {id: <?php echo $id; ?>},
        success: function(data) {
            opdata = data;
        }
    })
    return opdata;
}
var opdata = markersUsingSynchronousCallToAjax();
console.log("using a synchronous ajax call", opdata);


///// OPTION 2: callback 
function markersUsingCallback(callback) {
    $.post("id.php", {id: <?php echo $id; ?>})
    .done(function(data) {
        callback(data);
    });
}
markersUsingCallback(function(opdata){
    console.log("using a callback", opdata);
});



///// OPTION 3: promise 
function markersUsingPromise(callback) {
    return $.post("id.php", {id: <?php echo $id; ?>});
}
markersUsingPromise().done(function(opdata){
    console.log("using a promise", opdata);
});

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

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