I have a jQuery script:
$.ajax({
url: "/scripts/secure/development/ajax.asp",
type: "POST",
dataType: "text",
data: "cmd=addresses",
success: function(msg){
var arrRows = msg.split("#*#");
for(i=0;i<arrRows.length;i++){
var record_id = arrRows[i].split("|")[0];
var address = arrRows[i].split("|")[1];
getPoint(address,function(pnt){
var lat开发者_运维知识库itude = pnt.lat();
var longitude = pnt.lng();
$.ajax({
url: "/scripts/secure/development/ajax.asp",
type: "POST",
dataType: "text",
data: "cmd=update&rec_id="+record_id+"&lat="+latitude+"&lng="+longitude,
success: function(msg){
}
});
});
}
}
});
function getPoint(address,callback){
var geocoder = new GClientGeocoder();
geocoder.getLatLng(address,callback);
}
The script is designed to pull a delimited list of record_ids | addresses and loop through each one and get the geolocation of each address then update the record in the database with the lat and lng of the geo location.
My problem is this... In the second (inner) $.ajax call I need access to the record_id variable that I've defined just inside the for loop in order to update the correct record in the database however I can't seem to get access to that record_id variable inside the success function of the inner ajax post.
Please help! Thanks.
You need to create a closure like this:
var callback = (function(record_id)
{
return function(pnt)
{
var latitude = pnt.lat();
var longitude = pnt.lng();
$.ajax({
url: "/scripts/secure/development/ajax.asp",
type: "POST",
dataType: "text",
data: "cmd=update&rec_id="+record_id+"&lat="+latitude+"&lng="+longitude,
success: function(msg){
}
});
});
})(record_id);
getPoint(address, callback);
精彩评论