【发布时间】:2011-06-27 09:31:23
【问题描述】:
当脚本通常依赖于一些 ajax 或服务器响应时,我通常会像这样或类似的东西在 javascript 中构建我的脚本。我真的不认为这是最有效的处理方式,那么执行这些类型的脚本的更好方式是什么?
function someclass() {
//some internal variables here
this.var1 = null;
this.var2 = null;
...
//some ajax function which gets some critical information for the other functions
this.getAJAX = function() {
self = this;
urls = "someurlhere";
//jquery ajax function
$.ajax({
type: "GET",
url: url,
dataType: 'json',
complete: function (xhr, textStatus) {
//get the response from the server
data = JSON.parse(xhr.responseText);
//call the function which will process the information
self.processAJAX(data);
}
})
this.processAJAX = function(data) {
//set some of the internal variables here
//according to the response from the server
//now that the internal variables are set,
//I can call some other functions which will
//use the data somehow
this.doSomething();
}
this.doSomething = function() {
//do something here
}
}
所以我会使用这样的脚本:
//instantiate the class
foo = new someClass();
//get the information from the server
//and the processAjax function will eventually
//call the doSomething function
foo.getAjax();
所以我真的不喜欢这样,因为在使用脚本时并不清楚发生了什么。我希望能够做这样的事情:
//instantiate the class
foo = new someClass();
//get info from the server
//in this example, the processAJAX function will not call the doSomething
foo.getAjax();
//do something
foo.doSomething();
但这不起作用,因为通常来自服务器的响应需要一些时间,所以当调用 doSomething 时,还没有必要的信息,因此,该函数没有做它应该做的事情。
如何做到这一点?
我确信答案已经在 StackOverflow 上的某个地方,但是我找不到任何东西,所以我会很感激,无论是答案还是指向可以解释这一点的资源的链接,都可能在 StackOverflow 上。任何帮助表示赞赏。谢谢。
【问题讨论】:
标签: javascript ajax optimization