JavaScript回调被解雇的功能是完成之前(无jQuery的) [英] Javascript callback being fired before function is complete (no jQuery)

查看:103
本文介绍了JavaScript回调被解雇的功能是完成之前(无jQuery的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2 JavaScript函数,第一个是它是一个回调函数的函数,加载AJAX含量(经由另一功能),和一个第二。它们看起来像:

I have 2 javascript functions, the first being a function which loads ajax content (via another function), and a second which is a callback function. They look like:

function createReply(callBack){
    ajaxPage('test.html', 'next-reply');
    callBack();
}

function updateNext(){
    document.getElementById('next-reply').id  = "reply-item";
}

createReply(updateNext);

正如你所看到的,我打电话了 createReply()函数并传递它的名字的回调函数,在这种情况下, updateNext( )

As you can see, I am calling the createReply() function and passing it the name of the callback function, in this case updateNext()

createReply()函数,我调用另一个函数,它通过AJAX加载的内容。当这个函数结束时,回调应该被执行。回调改变正在被加载的AJAX内容div的ID。这是哪里的问题是发生

In the createReply() function, I am calling another function which loads content via ajax. When this function is complete, the callback is supposed to be executed. The callback changes the id of the div in which the ajax content is being loaded. This is where the problem is occuring

我收到错误:

Uncaught TypeError: Cannot set property 'innerHTML' of null 

哪个是说,它不能改变与该ID的元素的含量的下一回答的,因为它不存在,并且它不存在的原因是因为所述回调函数改变的ID,如果该元素。我们的目的是让回调触发Ajax内容加载后(即,在 ajaxPage()函数执行后)

Which is saying that it cannot change the content of the element with the id "next-reply" because it doesn't exist, and the reason it doesn't exist is because the callback function changes the id if that element. The intention is to have the callback fire after the ajax content has been loaded (ie; after the ajaxPage() function has been executed)

任何人都可以看到的问题是什么呢?有没有在普通的JavaScript实现的回调函数的更好的方式?

Can anyone see what the problem is? Is there a better way of implementing a callback function in plain javascript?

PS:没有jQuery的

推荐答案

正如指出的意见,这是由于这样的事实,Ajax调用异步发生。该 createReply 在运行的线程继续运行之前的响应从服务器返回。

As pointed out in the comments, this is due to the fact that AJAX calls happen asynchronously. The thread that createReply runs in continues to run before a response is returned from the server.

您将需要重新系数 ajaxPage 来接受引用回调,并调用它时,响应准备。是这样的:

You'll need to re-factor ajaxPage to accept a reference to callback, and call it when the response is ready. Something like:

function createReply(callBack){
    ajaxPage('test.html', 'next-reply', callBack);
}

然后,在ajaxPage:

Then, in ajaxPage:

function ajaxPage(url, id, callback){
   //Do AJAX stuff

   //When the response is returned:
   if(callback) callback();
}

这篇关于JavaScript回调被解雇的功能是完成之前(无jQuery的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆