Javascript jQuery post()/get() JSON 对象作为文档准备好之前的闭包函数
我试图找出处理文档准备好时需要发布/获取的 JSON 对象的最佳方法是什么,以便我可以运行另一个基于所述 JSON 对象构建 DOM 的函数。该对象也是每 30 秒到一分钟更新一次的对象。
我最初的想法是将其构建为一个闭包。即:
var myJSONobject = $.post(uri, function(data){return data;});
但是,我在文档准备就绪时运行的函数以及基于单击事件的函数无法识别该对象是否有效。它返回一个 JSON 对象,我使用 jsonlint.com 来确认该对象格式有效。所以我在想这取决于我如何处理这一系列事件。尽管对象可能是合法的,但在文档准备好之后才呈现该对象,从而在某种意义上破坏了功能。因为如果我采用相同的对象,它会吐出并将其硬编码为变量。我一直在编写的代码工作正常。所以现在我试图找出处理这个问题的最佳方法是什么,这样我的脚本就不会过早中断。两个人找出尝试将其调整为我现在的方式是否是正确的方法?在这种情况下,什么是好的实践逻辑?我应该将 JSON 对象加载到隐藏的 div 某处或文本区域中,然后将其传递给它还是什么?
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. This object is also something that updates every 30 seconds to a minute.
My initial thought was to build it out as a closure. i.e.:
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. It returns a JSON object, and I've used jsonlint.com
to confirm that the object format is valid. 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
$.post
函数实际上并不返回 success 函数的返回值,因此您不能只将myJSONobject
分配给它。你真正想做的是
但是要小心,你不能在调用
$.post
后立即访问myJSONobject
,你需要等到ajax调用成功。$.post
function does not actually return the return value of the success function, so you cannot just assignmyJSONobject
to it.What you really want to do is
But be careful, you can't access
myJSONobject
right after calling$.post
, you need to wait until the ajax call succeded.如果您在 document.ready 之前立即需要该对象,请使用 jsonp 技术,并将该脚本加载到文档
中。或者最好将其加载到
的末尾,并在其后加载需要它的脚本。
If you need the Object right away before document.ready, use the jsonp technology, and load that script inside documents
<head>
. Or better load it at the end of the<body>
, and the scripts that need it right after it.