Как yui3 io-form возвращает неудачу или успех? - PullRequest
0 голосов
/ 28 марта 2012

У меня есть следующее:

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);
});

Как вы узнаете, стоит ли заходить в onSucces onFailure. Что мне нужно вернуть из PHP?

1 Ответ

0 голосов
/ 06 июня 2012

Зависит от заголовка 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.
});
...