在向服务器发送 Ajax 请求,然后在 JavaScript 对象中的成功函数上返回数据时,我遇到了一个有点烦人的问题。我搜索了类似的问题,但没有一个与我的方式相同。
例如,我有以下代码用于在对象中发送请求:
function SomeObject ( someVar )
{
var someVar = someVar;
}
SomeObject.prototype.sendRequest = function ()
{
$.ajax(
{
url : "somePage.php",
type : "POST",
data :
{
someVar : someVar
},
success : this.parseSuccess
} );
};
SomeObject.prototype.parseSuccess = function ( data )
{
if ( data === "success" )
{
this.proceed(); // Error
}
else
{
alert( "Server failed request." );
this.proceed();
}
};
SomeObject.prototype.proceed = function ()
{
// Do something else
};
我知道这this.proceed()
会失败,因为this
不是SomeObject
实例。
不过,在请求完成后,如何有效地引用该对象?我发现我可以执行以下操作来实现我想要的,但感觉不合适,我想要一种更好的方式来处理 Ajax 调用:
SomeObject.prototype.sendRequest = function ()
{
var me = this;
$.ajax(
{
url : "somePage.php",
type : "POST",
data :
{
someVar : someVar
},
success : function ( data )
{
me.parseSuccess( data ); // Will work
}
} );
};
感谢您对此事的任何帮助。