我正在使用谷歌地图。我的地图数据来自php使用ajax响应。
我的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
不需要其他参数。
下面是一个使用$的示例。但是它只用于语法,不调用
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**函数已经返回一个承诺,所以你可以直接使用
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>
正如您所注意到的,在success函数中可以访问'result'数据。那么如何把它转换成另一个函数呢?您使用console.log(result)将数据打印到控制台。在不知不觉中,你几乎自己解决了这个问题。
在ajax调用的成功函数中调用初始化函数:
<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