Javascript 在文档准备就绪之前从服务器获取AJAX数据(jQuery)
我想从服务器获取一些数据,并用JavaScript将其写入全局数组。然后在DocumentReady中,我想使用这个数组创建一些新元素(选项)。我应该有一个包含此数据的全局数组,因为在第一次加载之后,客户端可以使用此数据修改用户界面Javascript 在文档准备就绪之前从服务器获取AJAX数据(jQuery),javascript,jquery,ajax,document-ready,Javascript,Jquery,Ajax,Document Ready,我想从服务器获取一些数据,并用JavaScript将其写入全局数组。然后在DocumentReady中,我想使用这个数组创建一些新元素(选项)。我应该有一个包含此数据的全局数组,因为在第一次加载之后,客户端可以使用此数据修改用户界面 $(document).ready(function () { UseAjaxQueryForFillGlobalArray(); MakingInterfaceUsingGlobalArray(); }); 但我有一个奇怪的行为,当
$(document).ready(function () {
UseAjaxQueryForFillGlobalArray();
MakingInterfaceUsingGlobalArray();
});
但我有一个奇怪的行为,当我调试页面时,我可以看到使用globalarray创建接口的方法首先起作用,在我使用方法UseAjaxQueryForFillGlobalArray通过AJAX获取数据之后,我没有加载数据的新接口(html选项)
如果我喜欢这个:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
然后在Firefox中工作正常,但在另一个web浏览器中第一次加载时不正确(例如,通过链接转到此页面)。但如果我使用F5刷新,我就有了正确的用户界面,可以通过AJAX加载到全局JS数组
如何修复它?也许我用的方法完全不正确
在评论后添加:
这是我的ajax函数:
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.
}
});
}
函数UseAjaxQueryForFillGlobalArray(){
var curUserId='';
var curLocale='';
$.ajax({
类型:“POST”,
url:“/segment.aspx/GetArrayForCF”,
数据:“{”userId:“'+curUserId+”,“curLocale:“'+curLocale+'”}”,
contentType:“应用程序/json;字符集=utf-8”,
数据类型:“json”,
成功:功能(msg){
//我正在从服务器解析字符串并填充数组。
}
});
}
我认为问题在于您不知道第一个函数何时返回,因为它是异步函数。因此,您应该只在回调中使用数组
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
这就像是死而复生,但我今天遇到了同样的问题,jQuery版本大于1.6具有以下功能: 我是这样用的:
UseAjaxQueryForFillGlobalArray();
$(document).ready(function () {
MakingInterfaceUsingGlobalArray();
});
$.holdReady(true);
var remoteJSONContent = null;
$.getJSON("http://www.example.com/remote.json", function(data) {
remoteJSONContent = data;
$.holdReady(false);
});
$(document).ready(function(){
console.log(remoteJSONContent);
});
没有使用holdReady
,我得到了空值,之后,我得到了内容
对于仍在搜索答案的人。您忘记实际添加示例的链接。向我们展示您的jQuery ajax代码。有一个属性(
async
)可能就是您所需要的。附带说明:对于初始页面呈现,我建议您在单个请求中传输所需的所有数据,而不是加载基本上“空白”的页面,然后通过ajax将数据加载到其中。我添加了ajax功能。谢谢!但我没有使用$.post,而是使用了$.ajax,因为服务器上有500个错误。