2012-03-27 51 views
0

我有以下几点:yui3 io-form如何返回失败或成功?

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

如何衣知道是否进入onFailure处的onSucces。我必须从PHP返回什么?

+0

有没有人有一个简洁的方式来传回一个声明错误的数组? – user1154863 2012-03-27 20:34:21

回答

0

这取决于返回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.JSO N,你需要包含'json-parse',例如:

YUI().use('json-parse', , function (Y) { 
    // JSON is available and ready for use. Add implementation 
    // code here. 
}); 
+0

另请参阅JSend(http://labs.omniti.com/labs/jsend)。 – Seth 2014-03-11 00:17:31

相关问题