my two ajax send request at the same time
I have a probl开发者_StackOverflow中文版em about my code. In my program, I have here an option box that will allow the user to choose what page did she/he want to show in my tblPlank
and tblSummary
(tblSummary and tblPlank were both jqgrid). Evrytime he chooses a page and click a button, it will call the function displayPageNum
. Now, my problem is, this two:
url:'processjson.php?path=' + encodeURI('getData/tally/page') + '&json=' + encodeURI(JSON.stringify(datas)),
and
url:'processjson.php?path=' + encodeURI('getReport/tallySummary') + '&json=' + encodeURI(JSON.stringify(datas)),
,
send request at the same time which sometimes makes my other table (or the other) dont display the right output. So how can I fix this to make it send request one at a time?
function displayPageNum(){
var flag = 0;
if ($("#page option:selected").text() != 'all'){
var datas = {
"SessionID": $.cookie("SessionID"),
"dataType":"data",
"transaction_id":$('.transactionID').attr('id'),
"page":$("#page option:selected").text()
};
$('#tblPlank').setGridParam({
url:'processjson.php?path=' + encodeURI('getData/tally/page') + '&json=' + encodeURI(JSON.stringify(datas)),
datatype: primeSettings.ajaxDataType
});
$('#tblPlank').trigger('reloadGrid');
flag =1;
if (flag == 1){
var datas = {
"SessionID": $.cookie("SessionID"),
"dataType":"data",
"transaction_num":$('.transactionID').val(),
"page":$("#page option:selected").text()
};
$('#tblSummary').setGridParam({
url:'processjson.php?path=' + encodeURI('getReport/tallySummary') + '&json=' + encodeURI(JSON.stringify(datas)),
datatype: primeSettings.ajaxDataType
});
$('#tblSummary').trigger('reloadGrid');
}
}
}
I put the flag variable just to make send the request one at a time, but still sending request at the same time.
I could see two ways:
1) Synchronous ajax request or
2) Send other ajax request when first one success.
Normally they are asynchronous.
Even better, you could use jQuery Deffered which allows you to have a success callback when both requests have completed.
var ajax1 = function (){
return $.get('first.html');
}
var ajax2 = function (){
return $.get('second.html');
}
$.when( ajax1(), ajax2()).then(function(){
alert('Both Done!');
});
However if you want to make sure that you cannot send more than 1 request at a time you can keep track of the request object.
var myRequest;
var ajaxRequest = function () {
if (!myRequest) {
var myRequest = $.get('myWebservice.html');
}
}
精彩评论