AJAX 是否有任何标准或消息传递框架?
现在我有一个使用 Ajax 加载内容的页面。因为我的内容中有一个复杂的数据输入表单,所以我需要验证表单中可能发生的某些事件。因此,经过我的测试驱动的一些调整后:
asyncShould("search customer list click", 3, function() {
stop(1000);
$('#content').show();
var forCustomerList = newCustomerListRequest();
var forShipAndCharge = newShipAndChargeRequest(forCustomerList);
forCustomerList.page = '../../vt/' + forCustomerList.page;
forShipAndCharge.page = 'helpers/helper.php';
forShipAndCharge.data = { 'action': 'shipAndCharge', 'DB': '11001' };
var originalComplete = forShipAndCharge.complete;
forShipAndCharge.complete = function(xhr, status) {
originalComplete(xhr, status);
ok($('#customer_edit').is(":visible"), 'Shows customer editor');
$('#search').click();
ok($('#customer_list').is(":visible"), 'Shows customer list');
ok($('#customer_edit').is(":hidden"), 'Does not show customer editor');
start();
};
testController.getContent(forShipAndCharge);
});
这是获取内容的控制器:
getContent: function (request) {
$.ajax({
type: 'GET',
url: request.page,
dataType: 'json',
data: request.data,
async: request.async,
success: request.success,
complete: request.complete
});
},
这是请求事件:
function newShipAndChargeRequest(serverRequest) {
var that = {
serverRequest: serverRequest,
page: 'nodes/orders/sc.php',
data: 'customer_id=-1',
complete: errorHandler,
success: function(msg) {
shipAndChargeHandler(msg);
initWhenCustomer(that.serverRequest);
},
async: true
};
return that;
}
这是一个成功处理程序:
function shipAndChargeHandler(msg) {
$('.contentContainer').html(msg.html);
if (msg.status == 'flash') {
flash(msg.flash);
}
}
在我的服务器端,我最终得到了一个如下所示的 JSON 结构:
$message['status'] = 'success';
$message['data'] = array();
$message['flash'] = '';
$message['html'] = '';
echo json_encode($message);
所以现在加载内容由两部分组成:
- HTML,这是表单的呈现方式。
- DATA,这是需要为表单加载的任何数据
- FLASH,任何验证或服务器错误
- STATUS 告诉客户端服务器上发生了什么。
我的问题是:这是在客户端处理事件消息的有效方法,还是我会走上心痛和痛苦的道路?