[英]Calling a function on ajax success
我必須使用ajax和httphandler將數據從SQL填充到jvectormap。
我可以獲取json來填充jvectormap,但我不知道如何傳遞從ajax獲取的數據
$.ajax({
url: 'CountryRegistrations.ashx',
type: 'POST',
success: function (data) {
var dataC = data;
},
error: function (data) {
alert("Error");
}
});
var countryData = [];
//for each country, set the code and value
$.each(dataC.countries, function () {
countryData[this.Country] = this.Count;
});
$( function () {
//World map by jvectormap
$('#world-map').vectorMap({
map: 'world_mill_en',
backgroundColor: "#fff",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
}
},
series: {
regions: [{
values: countryData,
scale: ["#3c8dbc", "#2D79A6"], //['#3E5E6B', '#A6BAC2'],
normalizeFunction: 'polynomial'
}]
},
onRegionLabelShow: function (e, el, code) {
var country = $.grep(dataC.countries, function (obj, index) {
return obj.Country == code;
})[0];
if (country != undefined) {
el.html(el.html() + ': ' + country.Count + ' new visitors');
}
}
});
})
我想將dataC從ajax傳遞到var CountryData,然后傳遞給jvectormap函數。
我得到的數據是json格式
"countries":[{"Country":"AE","Count":5},{"Country":"CH","Count":2},{"Country":"IN","Count":3},{"Country":"PK","Count":3},{"Country":"US","Count":2}]
以您的方式,您在ajax調用之后編寫的代碼將在ajax調用完成之前被調用,因為它是異步的
您可以這樣調用函數:
success: function (data) {
MyFunction(data);
}
在ajax調用之外的函數將被調用:
function MyFunction(data)
{
// do something here
}
在您的情況下:
function MyFunction(data)
{
var countryData = [];
//for each country, set the code and value
$.each(data.countries, function () {
countryData[this.Country] = this.Count;
});
$( function () {
//World map by jvectormap
$('#world-map').vectorMap({
map: 'world_mill_en',
backgroundColor: "#fff",
regionStyle: {
initial: {
fill: '#e4e4e4',
"fill-opacity": 1,
stroke: 'none',
"stroke-width": 0,
"stroke-opacity": 1
}
},
series: {
regions: [{
values: countryData,
scale: ["#3c8dbc", "#2D79A6"], //['#3E5E6B', '#A6BAC2'],
normalizeFunction: 'polynomial'
}]
},
onRegionLabelShow: function (e, el, code) {
var country = $.grep(dataC.countries, function (obj, index) {
return obj.Country == code;
})[0];
if (country != undefined) {
el.html(el.html() + ': ' + country.Count + ' new visitors');
}
}
});
})
}
只需在ajax調用中調用該函數即可:success:function(data){countryCall(data); },
founction countryCall(data) {
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.