ajax回调函数中如何传递对象

sxlfybb 2008-07-15 02:00:49
调用的地方使用的是jquery,也可以是普通的xmlhttp的请求,主要是回调函数的设置

 $.ajax({
type: "GET",
async:false,
url: g.ConfigError, //Requesting simple.xml
dataType: "xml", //Make sure that you specify the type of file you expecting (XML)
complete: this.setErrorList
});


this.setErrorList的定义

    setErrorList:function(data){
var errorList = null;
var objJson = $.xmlToJSON(data.responseXML);
if(objJson){
errorList = objJson.Err;
//alert(this.FileName)
if(_g.PermitOffline){
g_ErrorList = errorList;
}
this.ErrorList = errorList;
}
},


在回调函数中使用this.FileName或者this.ErrorList等对象的属性,都会提示未定义。
那如何设置才可以在回调函数中,使用被调用者的对象?因为回调函数相当于委托,其参数格式是固定的,我们不可以给它再加一个传入的对象参数。

我也想过使用全局变量来保存,作为对象中转。但是那样如果ajax频率比较大的话,抛开容易出错不说,系统开销也会很大。
...全文
1876 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
sxlfybb 2008-07-16
  • 打赏
  • 举报
回复
问题已经自行解决了,非常感谢你的提示。最终我是使用Function.call解决的。
sxlfybb 2008-07-15
  • 打赏
  • 举报
回复
我测试过了,虽然对象是有了,但是却是一个复制品,不是原对象的引用。
在回调函数中修改对象的属性后,原对象并没有发生任何改变。。。。
cgisir 2008-07-15
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 sxlfybb 的回复:]
我想就按你这个写法,估计还是不行。
...
[/Quote]
没试怎么知道不行?
而且你实现的这个和回调函数没有关系...
熟了就理解了...
sxlfybb 2008-07-15
  • 打赏
  • 举报
回复
我想就按你这个写法,估计还是不行。
jquery只是一个工具而已,其内部没有实现传递对象。

抛开jquery,我现在是想知道一个思路,或者说是一个设计模式,如何在回调中传递对象。

好像在settimeout时,函数传递对象的性质一样。
cgisir 2008-07-15
  • 打赏
  • 举报
回复
刚刚下了个JQ看下
这样试试
	getdata:function(){
this.call($.ajax);
$.ajax(jQuery.extend({
type: "GET",
async:false,
url: g.ConfigError,
dataType: "xml",
complete: this.setErrorList
},this));
},
sxlfybb 2008-07-15
  • 打赏
  • 举报
回复
我晕,明白你的意思了。

$.ajax一个ajax的封装,是jquery库中定义好的。相当于新建了一个xmlhttp请求,从服务器上读取一个文件的数据,并且在完成读取后,触发complete指定的回调函数,即:this.setErrorList。
而这个函数的定义必须是function fn(data){}
cgisir 2008-07-15
  • 打赏
  • 举报
回复
那也要看你的$.ajax是怎么定义的啊
可以这样试试
getdata:function(){
this.call($.ajax);
$.ajax({
type: "GET",
async:false,
url: g.ConfigError,
dataType: "xml",
complete: this.setErrorList
});
},
sxlfybb 2008-07-15
  • 打赏
  • 举报
回复
格式规范一点,上面的看起来太累了。

function aaa()
{
this.a=0;
this.str="sdf";
}
aaa.prototype={
getdata:function(){
$.ajax({
type: "GET",
async:false,
url: g.ConfigError,
dataType: "xml",
complete: this.setErrorList
});
},
setErrorList:function(data){
this.str=data;
}
}
sxlfybb 2008-07-15
  • 打赏
  • 举报
回复
this是指当前我自定义的一个对象,不是指$
比如
function aaa()
{
this.a=0;
this.str="sdf";
}
aaa.prototype={
getdata:function(){
$.ajax({
type: "GET",
async:false,
url: g.ConfigError,
dataType: "xml",
complete: this.setErrorList
});

},
setErrorList:function(data){
this.str=data;
}
}


主要作用是在获取到数据之后,将相关数据赋于本对象的属性。
cgisir 2008-07-15
  • 打赏
  • 举报
回复
看你ajax怎么写的了

试试 $.ajax.setErrorList = function(){alert('this.errorList')}
sxlfybb 2008-07-15
  • 打赏
  • 举报
回复
这个问题我想主要是由于线程不同而产生的。有相关经验的大大们,现身解说一下,谢谢。

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧