Pet*_*ger 3 javascript ajax jquery json prototype
我正在使用此处提出的建议(http://www.odetocode.com/articles/473.aspx)使用模拟命名空间和原型设计编写JavaScript AJAX网络聊天系统.
在我的一个原型方法中,我在jQuery中调用$ .ajax方法.我当时想要做的是将返回的JSON数据传递到JavaScript webchat命名空间内的方法中.
问题似乎是因为我创建了一个JavaScript webchat的实例,我不能直接在其中调用一个方法,因为我需要通过实例解决它.
下面代码中的关键部分是
success: function(data, textStatus) {
this.GetUpdate_Success(data)
},
Run Code Online (Sandbox Code Playgroud)
我在想,因为我们在$ .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);
}
Run Code Online (Sandbox Code Playgroud)
解决此问题的最简单方法是创建一个this在所需的适当范围内引用的变量. this和JavaScript在大多数语言的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);
}
});
},
Run Code Online (Sandbox Code Playgroud)