在文档准备好之前从服务器获取AJAX数据(jQuery) [英] Get AJAX data from server before document ready (jQuery)
问题描述
我想从服务器获取一些数据并用JavaScript将其写入全局数组。然后在文档就绪中我想使用这个数组来创建一些新元素(选项)。我应该有这个数据的全局数组,因为在第一次加载客户端后可以使用这些数据修改用户界面。
I want take some data from server and write it to global array in JavaScript. Then in document ready I want to use this array to create some new elements (options). I should have global array with this data, because after first load client can modify user interface using this data.
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
但我有奇怪的行为,当我调试页面时,我可以看到该方法 MakingInterfaceUsingGlobalArray 首先工作,刚刚通过AJAX使用方法 UseAjaxQueryForFillGlobalArray 获取数据后,我没有带有加载数据的新接口(html选项)。
But I have strange behavior, when I debug page, I can see that method MakingInterfaceUsingGlobalArray working first, and just after I get data via AJAX with method UseAjaxQueryForFillGlobalArray and I don't have new interface(html options) with loaded data.
如果我喜欢这样:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
然后在Firefox工作正常,但在第一次加载时其他网络浏览器不正确(例如转到这个页面的链接)。但如果我用F5刷新,我有正确的用户界面,它通过AJAX加载到全局JS数组。
Then in Firefox working fine, but in another web-browsers incorrect in first load (for example go to this page by link). But if I refreshing by F5, I have correct user interface which loaded via AJAX to global JS array.
如何解决?也许我使用完全不正确的方式?
How to fix it? Maybe I using totally incorrect way?
评论后添加:
这是我的ajax函数:
This is my ajax function:
function UseAjaxQueryForFillGlobalArray(){
var curUserId = '<%= Master.CurrentUserDetails.Id %>';
var curLocale = '<%= Master.CurrentLocale %>';
$.ajax({
type: "POST",
url: "/segment.aspx/GetArrayForCF",
data: '{"userId":"' + curUserId + '","curLocale":"' + curLocale + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
//here is I doing parse my string from server and fill arrays.
}
});
}
推荐答案
我认为问题是你不确切知道第一个函数何时返回,因为它是异步的。所以你应该只在回调中使用数组
I think that the problem is that you don't know exactly when the first function returns, since it'a asynchronous. So you should use the array in the callback only
function UseAjaxQueryForFillGlobalArray() {
// make the call
$.post(url, data, function() {
// let's be sure that the dom is ready
$(document).ready(function () {
// use the array
MakingInterfaceUsingGlobalArray();
}
}
}();// invoke the function
这篇关于在文档准备好之前从服务器获取AJAX数据(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!