我有以下几点:
YUI().use("io-form",
function(Y) {
var cfg = {
method: 'POST',
form: {
id: 'subscribe-form',
useDisabled: false
}
};
function login() {
Y.io('process.php', cfg);
Y.on('io:success', onSuccess, this);
Y.on('io:failure', onFailure, this);
};
function onSuccess(id,response,args) {
document.getElementById('myformmsg').innerHTML = response.responseText;
document.forms['myform'].reset();
};
function onFailure(id,response,args) {
document.getElementById('myformmsg').innerHTML = "Error, retry...";
document.forms['myform'].reset();
};
Y.on('click', login, '#myformbutton', this, true);
});yui如何知道是否进入onFailure的onSucces。我必须从PHP返回什么?
发布于 2012-06-06 16:22:59
这取决于返回的http状态码的头部。假设状态码为200,它将转到onSuccess。假设状态代码500 (内部服务器错误),它将转到onFailure。
HTTP状态代码列表:http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
如果你在php中有一些致命错误,它仍然会返回状态200,因为请求成功了。
如果你想处理php错误,我建议你像每次成功时一样返回一个json:
{
status: 0, // Let say 0 for OK, -1 for Error, you can define more by yourself
results: <anything you want here>,
errors: <errors message/errors code for your ajax handler to handle>
}它可以在php中像这样完成:
$response = array(
'status' => 0,
'results' => 'something good ...',
'errors' => 'error message if status is -1'
);
echo json_encode($response);在您的javascript中,您将像这样处理:
function onSuccess(id,response,args) {
var responseObj = Y.JSON.parse(response);
if (responseObj.status === 0) {
// Request and process by php successful
}
else {
// Error handling
alert(responseObj.errors);
}
};记住,如果你想使用Y.JSON,你需要包含'json-parse',例如:
YUI().use('json-parse', , function (Y) {
// JSON is available and ready for use. Add implementation
// code here.
});https://stackoverflow.com/questions/9897225
复制相似问题