I have the following code .
var last_id =开发者_StackOverflow社区 '';
$('.products').each(function(){
$.ajax({
type: "POST",
url: "index.php",
data: 'id='+last_id,
success: function(id){
last_id = id;
}
});
});
My problem is that , i want to get the last inserted id from ajax success and pass it to ajax when id call on second time. but now it can't get the last_id and in second time it again send as empty string But when i alert it in ajax success it alert the last id ? How can i achieved it ?
It won't work because when you send the second request, the first request's response hasn't arrived yet. That's the way it is because the requests you are sending are all asynchronous, so the second request won't wait for the first request to complete. That's why an empty string is being sent the second time too.
One way to send synchronous requests is to set async
option to false
.
Go to this link and search for the async
option there to find a proper explanation.
But you should note that sending synchronous requests may temporarily block the browser, because it waits for the request to complete before doing anything else.
$.ajax();
is asynchronous, meaning it branching off from your code and executes immediately while your code continues to run. So all your ajax calls start at nearly the same time before any of them return. You could use 'async': false,
in your params for ajax, but this might freeze the browser until all requests are complete.
You could get around this by waiting until the callback to make the next call asynchronously:
var last_id = '', count = 0;
(function getId(){
$.ajax({
type: "POST",
url: "index.php",
data: 'id='+last_id,
success: function(id){
last_id = id;
if(++count < $('.products').length)
getId();
}
});
});
})();
But
I think in your situation it would be better to make one request and have the server respond with a JSON array of Id's.
async: false in ajax function options will help. But I think you are going in wrong way :) You shouldn't execute so many ajax queries.
Does the Ajax call return JSON data? If so try:
success: function(data){
last_id = data.id;
}
or something similar.
you have to wait for each ajax
var pro=$('.products').lenght;
last_id(0,"");
function last_id(index,lastid){
$.ajax({
type: "POST",
url: "index.php",
data: 'id='+lastid,
success: function(id){
if(index<pro.length){
last_id(index+1,id);
}
}
});
});
}
精彩评论