[英]Javascript jQuery post()/get() JSON object as closure function before document ready
I'm trying to figure out what the best way to handle a JSON object that I need to post/get when the document is ready so I can then run over another function that builds out the DOM based on said JSON object.我试图找出处理文档准备就绪时需要发布/获取的 JSON 对象的最佳方法,以便我可以运行另一个函数,该函数基于所述 JSON 对象构建 DOM。 This object is also something that updates every 30 seconds to a minute.
这个对象也是每 30 秒到一分钟更新一次的东西。
My initial thought was to build it out as a closure.我最初的想法是将它构建为一个闭包。 ie:
IE:
var myJSONobject = $.post(uri, function(data){return data;});
however the function I run when the for document ready, and functions I base on click events don't recognize the object as being valid.但是,我在 for 文档准备就绪时运行的函数,以及我基于单击事件的函数无法将对象识别为有效。 It returns a JSON object, and I've used
jsonlint.com
to confirm that the object format is valid.它返回一个 JSON 对象,我已经使用
jsonlint.com
确认对象格式有效。 So I am thinking its in how I am handling the string of events.所以我在考虑我如何处理一系列事件。 Where the object though it may be legit is being rendered after the document ready thus breaking the functionality in a sense.
在文档准备好之后渲染对象虽然它可能是合法的,因此在某种意义上破坏了功能。 Cause if I take the same object it spits out and hard code it in as a variable.
因为如果我把它吐出来的同一个对象硬编码为一个变量。 the code I've been working on works fine.
我一直在处理的代码工作正常。 So now I am trying to figure out whats my best approach to handling this so one, my script doesn't break prematurely.
所以现在我想弄清楚我处理这个问题的最佳方法是什么,我的脚本不会过早地中断。 and two find out if trying to adapt this as a closure the way I am is the right way?
和两个找出尝试将其作为闭包调整我的方式是否正确? Whats a good practice logic in this type of scenario?
在这种情况下,什么是好的实践逻辑? Should I load the JSON object into a hidden div somewhere or text area and pass it through that or what?
我应该将 JSON 对象加载到某个地方或文本区域的隐藏 div 中并通过它还是什么?
$.post
function does not actually return the return value of the success function, so you cannot just assign myJSONobject
to it. $.post
函数实际上并不返回成功函数的返回值,因此您不能只将myJSONobject
分配给它。
What you really want to do is你真正想做的是
var myJSONobject;
$.post(uri, function(data){
myJSONobject = data;
// OR work with data here
});
// You cannot use myJSONobject right away
But be careful, you can't access myJSONobject
right after calling $.post
, you need to wait until the ajax call succeded.但是要小心,在调用
$.post
之后你不能立即访问myJSONobject
,你需要等到 ajax 调用成功。
If you need the Object right away before document.ready, use the jsonp technology, and load that script inside documents <head>
.如果您在 document.ready 之前立即需要对象,请使用 jsonp 技术,并将该脚本加载到文档
<head>
。 Or better load it at the end of the <body>
, and the scripts that need it right after it.或者最好在
<body>
的末尾加载它,以及在它之后需要它的脚本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.