微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Javascript“命名空间”和jQuery AJAX

我正在使用此处提出的建议(http://www.odetocode.com/articles/473.aspx),使用模拟的Namespacing和原型制作JavaScript AJAX网络聊天系统.

在我的一种原型方法中,我在jQuery中调用$.ajax方法.然后,我要做的就是将返回的JSON数据传递到JavaScript网络聊天命名空间中的方法中.

问题似乎是因为我已经创建了JavaScript网络聊天的实例,无法直接在其中调用方法,因为我需要通过实例来解决它.

以下代码中的关键部分是

            success: function(data, textStatus) {
                this.GetUpdate_Success(data)
            },

我在想,因为我们在$.ajax()方法中,所以它不再引用我们的WebchatV3对象.

完整的JavaScript代码如下所示:

/// <reference path="/JavaScript/jquery-1.3.2-vsdoc2.js" />

// Simulated 'namespace'
var AvonAndSomerset = {}

// Chatroom run time data
AvonAndSomerset.WebchatV3 = function(memberId, passcode) {
    this.Members = new Array(); // Members in the chatroom
    this.Questions = new Array(); // The questions queue in the chatroom

// Details about the current user
this.currentMember = new AvonAndSomerset.WebchatV3.Member(memberId, passcode, null, null, null, null, null);

    // Set-up AJAX defaults
    $.ajaxSetup({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json" });
}

AvonAndSomerset.WebchatV3.prototype =
{
    // Get latest Member,Quetsion,Transcript and Room data from server
    GetUpdate: function(StartUp) {

        $.ajax({ url: "JSON.aspx/Members_GetChanges",
            data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
            success: function(data, textStatus) {
                this.GetUpdate_Success(data)
            },
            error: function(result) {
                alert('Members_GetChanges() Failed: ' + result.responseText);
            }
        });
    },
    // Callback - on success of GetUpdate()
    GetUpdate_Success: function(data) {
        alert('The AJAX call was successful!');
    },
    // Does the MemberID exist in the local array?
    Members_DoesExist: function(MemberID) {
        alert('Searching for ' + MemberID);

        alert(this.Members.length);
    }

解决方法:

解决此问题的最简单方法是在所需的适当范围内创建一个引用此变量的变量.在大多数语言中,此和范围在javascript中的工作方式不同,在这种情况下,它是指传递给函数的对象.

// Get latest Member,Quetsion,Transcript and Room data from server
GetUpdate: function(StartUp) {
    //here
    var self = this;
    $.ajax({ url: "JSON.aspx/Members_GetChanges",
        data: "{ MemberID: " + this.currentMember.memberId + ", Passcode: \"" + this.currentMember.passcode + "\", ReturnAll: " + StartUp + " }",
        success: function(data, textStatus) {
            self.GetUpdate_Success(data)
        },
        error: function(result) {
            alert('Members_GetChanges() Failed: ' + result.responseText);
        }
    });
},

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐