Javascript 与 JSON 请求同步
如何确保一段代码在执行另一段代码之前已完全执行?我向服务器发送一些 ajax 请求,然后使用返回的数据生成网页的其余部分。问题是,我需要在网页中拥有所有数据才能继续执行其余代码,因为该代码将影响已生成的内容,并且该代码在 json 请求之前运行,所有这些都已完成。 ..有什么方法可以确保这种情况不会发生吗?我设法通过执行请求然后要求用户按下按钮来解决这个问题,但这是一种完全没有意义的做法。
有什么想法吗?
下面是一些代码: 问题是第二行在第一行之前执行(有很多对类似 JSON 函数的调用)。
$.getJSON(url, function(data){ $("#mycontent").append("..... stuff here...... create loads of dibs with class set to mydivclass"); });
...
$("div.mydivclass").hide();
不幸的是,我无法使用ajax同步属性,因为:“dataType:”jsonp“请求不支持同步操作”
How can I make sure that a piece of code has executed completely before executing another? I am sending some ajax requests to a server and then using the returned data to generate the rest of the webpage. the things is, is that i need to have all that data in the webpage to proceed with the rest of the code as that code will affect what has been generated and, that code, runs before the json requests and all of that have finished... is there any way I can make sure this does not happen? I managed to solve it by performing the requests and then asking the user to press a button but that is a total no-sense way of doing it.
Any ideas?
Here is some code: The problem is that the second line is executed before the first (there are many calls to similar JSON functions).
$.getJSON(url, function(data){ $("#mycontent").append("..... stuff here...... create loads of dibs with class set to mydivclass"); });
...
$("div.mydivclass").hide();
Unforunately I cannot use the ajax synchronous property because: "dataType: "jsonp" requests do not support synchronous operations"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用的是 jQuery 1.5+,您可以使用 deferreds 来解决您的问题:
有一篇关于该主题的优秀文章,您也应该阅读作者:Eric海因兹。他给出了一些例子来说明你正试图解决的问题类型。
If you are using jQuery 1.5+ you can make use of deferreds to solve your issue:
There is an excellent article on the topic that you should read up on as well by Eric Hynds. He gives some examples of exactly the kind of problem you are trying to solve.
jquery请求默认是异步的,所以你的代码不会等待响应,所以你不能保证请求之后的代码会在响应之后执行,所以你可以通过设置 async 属性 false 来设置请求同步,现在请求是同步,您可以保证其余代码将在服务器响应后执行,
像这样 。
jquery requests are asynchonize by default , so your code does not wait for the response , so you have no guarantee that code after request will execute after the response , so you can set the request synchronize by set the async property false , now the request is synchronize and you can gurantee the rest of the code will execute after the response from the server ,
like this .