Dưới đây là cách chúng tôi đã triển khai Ajax trên Google App Engine, nhưng ý tưởng có thể được khái quát hóa thành các nền tảng khác.
Chúng tôi có một kịch bản xử lý cho các yêu cầu Ajax đáp ứng tối đa - với các phản hồi JSON. Cấu trúc trông giống như thế này (đây là một đoạn trích từ một handler kịch bản tiêu chuẩn GAE):
def Get(self, user):
self.handleRequest()
def Post(self, user):
self.handleRequest()
def handleRequest(self):
'''
A dictionary that maps an operation name to a command.
aka: a dispatcher map.
'''
operationMap = {'getfriends': [GetFriendsCommand],
'requestfriend': [RequestFriendCommand, [self.request.get('id')]],
'confirmfriend': [ConfirmFriendCommand, [self.request.get('id')]],
'ignorefriendrequest': [IgnoreFriendRequestCommand, [self.request.get('id')]],
'deletefriend': [DeleteFriendCommand, [self.request.get('id')]]}
# Delegate the request to the matching command class here.
Các lệnh là một thực hiện đơn giản của mẫu lệnh:
class Command():
""" A simple command pattern.
"""
_valid = False
def validate(self):
""" Validates input. Sanitize user input here.
"""
self._valid = True
def _do_execute(self):
""" Executes the command.
Override this in subclasses.
"""
pass
@property
def valid(self):
return self._valid
def execute(self):
""" Override _do_execute rather than this.
"""
try:
self.validate()
except:
raise
return self._do_execute()
# Make it easy to invoke commands:
# So command() is equivalent to command.execute()
__call__ = execute
Về phía khách hàng, chúng tôi tạo một đại biểu Ajax. Prototype.js giúp dễ dàng viết và hiểu. Dưới đây là một đoạn trích:
/**
* Ajax API
*
* You should create a new instance for every call.
*/
var AjaxAPI = Class.create({
/* Service URL */
url: HOME_PATH+"ajax/",
/* Function to call on results */
resultCallback: null,
/* Function to call on faults. Implementation not shown */
faultCallback: null,
/* Constructor/Initializer */
initialize: function(resultCallback, faultCallback){
this.resultCallback = resultCallback;
this.faultCallback = faultCallback;
},
requestFriend: function(friendId){
return new Ajax.Request(this.url + '?op=requestFriend',
{method: 'post',
parameters: {'id': friendId},
onComplete: this.resultCallback
});
},
getFriends: function(){
return new Ajax.Request(this.url + '?op=getfriends',
{method: 'get',
onComplete: this.resultCallback
});
}
});
để gọi các đại biểu, bạn làm như sau:
new AjaxApi(resultHandlerFunction, faultHandlerFunction).getFriends()
Tôi hy vọng điều này sẽ giúp!
http://code.google.com/webtoolkit/doc/latest/tutorial/appengine.html <- Vị trí mới nhất của hướng dẫn ở trên. Chúc tôi có đại diện để chỉnh sửa nó. ;) – Drew
@Drew - Đã cập nhật URL trong câu trả lời. Cảm ơn cho những người đứng đầu lên. –
Cảm ơn Dave. Ah, tôi cho rằng quy tắc này có khả năng sử dụng Google Web Toolkit làm khung công tác AJAX cho GAE. Quá tệ! Có khung nào khác không? – Graviton