gpt4 book ai didi

javascript - jQuery 对 javascript 类方法的 AJAX 调用

转载 作者:数据小太阳 更新时间:2023-10-29 05:48:59 24 4
gpt4 key购买 nike

我是 jQuery 工作流程的新手,我想设置一个使用内部方法发出 AJAX 请求的 javascript 类。当请求成功返回时,jQuery AJAX 回调应该调用类本身拥有的方法。那是代码:

function IXClock()
{
this.m_intervalID = 0;

this.startClock = function ()
{
this.m_intervalID = setInterval(this.tictac, 500);
}

this.stopClock = function ()
{
clearInterval(this.m_intervalID);
}

this.setClockTime = function(p_strTime)
{
$('#clock').html(p_strTime);
}

this.tictac = function ()
{
$.ajax
({
type: 'POST',
url: '/rap/rapClock.php',
complete: function (data)
{
this.setClockTime(data);
}
});
}

}

该类代表一个时钟,带有一个在服务器端请求“现在几点”的内部方法 (tictac)。在服务器说出时间后,jQuery 的 AJAX 方法应该调用 IXClock 类的 setClockTime 方法。 invoke 方法将更新 html 页面中的#clock div 项。

问题是方法 this.setClockTime() 结果未知,javascript 返回“this.setClockTime 不是函数”错误。

问题是:有没有办法从 jQuery 的 AJAX 回调中调用类方法?

最佳答案

我认为问题在于您的回调函数中的this 与引用IXClockthis 不同。尝试:

var thisClass = this ;
this.tictac = function ()
{
$.ajax
({
type: 'POST',
url: '/rap/rapClock.php',
complete: function (data)
{
thisClass.setClockTime(data);
}
});
}

测试用例(添加到已经加载了 jQuery 的站点):

function uClass () {
this.testFunction = function(input) {
alert(input) ;
}
this.ajaxFunction = function() {
var myClass = this ;
$.ajax({
type: 'POST',
url: '/',
complete: function(data) {
alert(myClass.testFunction) ;
myClass.testFunction(data) ;
this.testFunction(data) ;
}
}) ;
}
}

var k = new uClass() ;
k.ajaxFunction() ;

关于javascript - jQuery 对 javascript 类方法的 AJAX 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3708110/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com