[英]How to run success function with JQuery getJSON?
我想將數據推送到數組,但是由於AJAX的異步性,因此不確定如何處理。
我似乎無法在網上找到有關使用getJSON完成此操作的完整示例。
我一直在這里遵循文檔,沒有運氣/
我努力了:
var jsonLtdLng="https://maps.googleapis.com/maps/api/geocode/json?address=" + addressval;
var latlng;
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
latlng = {lat: lat, lng: lng};
}).done(function() {
markerlocations.push(latlng);
})//END JSON
和:
var jsonLtdLng =“ https://maps.googleapis.com/maps/api/geocode/json?address=” + addressval; var latlng;
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
latlng = {lat: lat, lng: lng};
markerlocations.push(latlng);
});
以及沒有任何結果的變化。
有誰知道這樣做的正確方法,可以指出正確的方向嗎?
您需要將push()
送到success
處理程序中的數組,該處理程序可以訪問從請求返回的數據。 您最好將對象添加到數組中,而不要手動修改JSON字符串。 從那里,您可以將數組傳遞給需要執行的任何函數。 嘗試這個:
var markerlocations = [];
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat; // note 'lat' here, not 'lng'
var lng = data.results[0].geometry.location.lng;
markerlocations.push({ lat: lat, lng: lng });
doSomethingWithTheArray(markerlocations);
});
function doSomethingWithTheArray(arr) {
for (var i = 0; i < arr.length; i++) {
console.log(arr[i].lat, arr[i].lng);
}
}
嘗試這個。 使用foreach創建數組。 然后根據需要推送/追加數組。
$.getJSON("url here", function(data) {
$.each(data, function(key, value){
// your custom code here
var latlng = 'code you want';
});
markerlocations.push(latlng);
});
您需要在getJSON()函數外部聲明一個空數組。 然后可以在getJSON回調中訪問它。
var markerlocations = [];
$.getJSON(jsonLtdLng, function (data) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
markerlocations.push({ lat: lat, lng: lng });
});
function(data)...是在獲得響應后立即執行的回調函數。 在這種情況下,您不需要其他的done()方法。
var jsonLtdLng="https://maps.googleapis.com/maps/api/geocode/json?address=new york"; var latlng; var markerlocations = []; $.getJSON(jsonLtdLng, function (data) { var lat = data.results[0].geometry.location.lat; var lng = data.results[0].geometry.location.lng; latlng = {lat: lat, lng: lng}; markerlocations.push(latlng); // just for testing for(var i = 0; i < markerlocations.length; i++){ alert(markerlocations[i].lat + '===' + markerlocations[i].lng); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.