2012-03-27 54 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

相關問題