How can I pass variables in loop to a PHP file using AJAX?
var lat;
var lng;
var array = [ 22.399602, 114.041176, 22.344043, 114.0168, 22.327529, 114.087181 ];
console.log(array);
for (var i = 0; i < 6; i += 2) {
lat = array[i];
console.log("lat" + i + "=" + lat);
for(var j = i + 1; j <= i + 1; j++) {
lng = array[j];
console.log("lng" + j + "=" + lng);
}
}
My array is here:
In this case I want pass each lat
and long
to my database. My database will looks like this:
username: Neo
lat=22.399602
long=114.041176
lat=22.344043
long=114.0168
lat=22.327529
long=114.087181
I also test this AJAX function but it isn't working for an array.
$.post('send.php', { latitude: lat, longitude: lng }, function(data) {
$('#result').html(data);
});
What should I do now?
If you were to structure your initial array in a more logical manner the problem would be much simpler for you. Consider:
function sendlatlng(lat,lng){
var http=new XMLHttpRequest();
http.onreadystatechange=function(){
if( http.readyState==4 && http.status==200 ) console.info( http.response );
};
var headers={
'Content-type': 'application/x-www-form-urlencoded'
};
http.open('POST', '/send.php', true );
for( header in headers ) http.setRequestHeader( header, headers[ header ] );
http.send( 'lat='+lat+'&lng='+lng );
}
var array = [ [22.399602, 114.041176], [22.344043, 114.0168], [22.327529, 114.087181] ];
for( i=0; i < array.length; i++ ){
lat=array[ i ][ 0 ];
lng=array[ i ][ 1 ]
console.log( 'lat: %s lng: %s',lat,lng );
sendlatlng.call( this, lat, lng );
}
if you are certain that array
will contain latitude and longitude one after the other then you don't need a nested loop.
var lat;
var lng;
var array = [22.399602,114.041176 , 22.344043,114.0168 , 22.327529,114.087181];
//console.log(array);
for(var i=0;i<array.length;i+=2)
{
lat=array[i];
long = array[i+1];
console.log(lat+" "+long);
$.post('send.php', {latitude:lat, longitude:long},
function(data)
{
$('#result').html(data);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.