2012-03-27 3 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); 
}); 

どのようにYUIがONFAILUREのonSuccesに入るかどうかを知っているん。 PHPから何を返す必要がありますか?

+0

誰もが戻ってエラーを述べた配列を渡すためにきちんとした方法がありますか? – user1154863

答えて

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-解析」を含める例が必要:

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

関連する問題