JQuery : Forcing page to halt until data is finished loading
I might be wrong about what is actually happening here but i have 3 Html.dropdownlists. And im using jquery to handle filtering which does actually work. However, there is some odd behaviour which i think might be because data isnt finished loading before the next function is called.
For instance:
Some background. Company: Owns several field offices Field Office: Owns several facilties So logically, when you change company, field offices should change, which then changes facilities.
$(function () {
$(document).ready(function () {
var cid = $("#CompanyId").val();
$.post("/ManifestSearch/GetFilteredFieldOffices", { id: cid }, function (data) {
$("#FieldOfficeId").loadSelect(data);
});
var fid = $("#FieldOfficeId").val();
$.post("/ManifestSearch/GetFilteredFacilities", { id: fid }, function (data) {
$("#FacilityId").loadSelect(data);
});
});
});
Now, when the page loads, everything looks fine. All the dropdownlists have the correct data.
When i change company, this calls.
$(function () {
$('#CompanyId').change(function () {
var cid = $(this).val();
$.post("/ManifestSearch/GetFilteredFieldOffices", { id: cid }, function (data) {
$("#FieldOfficeId").loadSelect(data);
});
var fid = $("#FieldOfficeId").val();
$.post("/ManifestSearch/GetFilteredFacilities", { id: fid }, function (data) {
$("#FacilityId").loadSelect(data);
});
});
});
This changes the field offices to the correct list, however facilities changes to whatever field offices was set to befor开发者_JS百科e the company change occured. I dont know enough about jquery to figure out exactly what is going on, but my instinct tells me that the two posts are happening at the same time, and the second post happens before the first one is finished.
It's the nature of an asynchronous request.. you don't know which order they will finish in so you can't always assume the data from the first one will be available to the second one.
Ideally, your second request should be within the onSuccess callback function of the first request, with an onFailure/onError function handler to take care of any problems that arise.
精彩评论