繁体   English   中英

如何在另一个JavaScript中使用Ajax响应数据

[英]how to use ajax response data in another javascript

我正在使用谷歌地图。我的地图数据来自使用ajax响应的php。

我的ajax代码:

<script type="text/javascript">

    $.ajax({
    type: "POST",
    url: "mapajax.php",
    dataType:'text',
    success: function (result) {

                console.log(result); 

    }
    });
</script>

现在,我需要将响应数据放入地图var location

function initialize() {
    var locations = [
      //Now here I put my ajax response result
    ];

我怎样才能做到这一点?

您将不得不稍微重构代码。 我假设您从成功回调中调用initialize

locations数组作为参数传递给initialize

function initialize(locations) { ... }

$.ajax({
    type: "POST",
    url: "mapajax.php",
    dataType:'text',
    success: function (result) {
        initialize(result); 
    }
});

然后,您可以减少更多的操作并success: initialize ,只要initialize不需要其他参数即可。

这是一个使用$ .when的例子,但它仅用于SYNTAX而不打电话

http://jsfiddle.net/2y6689mu/

// Returns a deferred object
function mapData(){ return $.ajax({
    type: "POST",
    url: "mapajax.php",
    dataType:'text'
});
}
// This is the magic where it waits for the data to be resolved
$.when( mapData() ).then( initialize, errorHandler );

EDIT **函数已经返回了一个Promise,因此您可以使用

mapData().then()

每个代号注释

这是使用回调函数完成的, http://recurial.com/programming/understanding-callback-functions-in-javascript/ ,如果您想了解这些内容,可以使用以下链接。 让我们在这里查看您当前的代码:

<script type="text/javascript">

$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
    console.log(result); 
}
});
</script>

如您所见,成功函数中可以访问“结果”数据。 那么如何将其传输到另一个功能? 您使用console.log(result)将数据打印到控制台。 如果没有意识到这一点,您几乎可以自己解决问题。

只需在ajax调用的成功函数内调用initialize函数:

<script type="text/javascript">

$.ajax({
type: "POST",
url: "mapajax.php",
dataType:'text',
success: function (result) {
    initialize(result); 
}
});

</script>

$.ajax()mapajax.php调用text预期dataType响应吗?

尝试

$(function () {
    function initialize(data) {
        var locations = [
        //Now here I put my ajax response result
        ];
        // "put my ajax response result"
        // utilizing `Array.prototype.push()`
        locations.push(data);
        // do stuff
        // with `locations` data, e.g., 
        return console.log(JSON.parse(locations));
    };
    $.ajax({
        type: "POST",
        url: "mapajax.php",
        dataType: 'text',
        success: function (result) {
            initialize(result);
        }
    });
});

jsfiddle http://jsfiddle.net/guest271314/maaxoy91/

看到

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

暂无
暂无

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

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