$.ajax({ type: 'post', url: "/ajax/url.php", data: {}, dataType: 'json', cache: false, beforeSend: function(XMLHttpRequest){ console.log(XMLHttpRequest); }, success: function(XMLHttpRequest, textStatus){ console.log(XMLHttpRequest); console.log(textStatus); }, error: function(XMLHttpRequest, textStatus, errorThrown){ console.log(XMLHttpRequest); console.log(textStatus); console.log(errorThrown); }, complete: function(XMLHttpRequest, textStatus){ console.log(XMLHttpRequest); console.log(textStatus); }, dataFilter: function(data, type){ console.log(data); console.log(type); } });
jQUery 1.8以上の書き方(上記でも動くけど)
$.ajax({ url: "ajax.html", }).done(function(data) { alert('success!!'); }).fail(function(data) { alert('error!!!'); }).always(function(data) { alert('complete!!!'); });
進捗の取得
$.ajax({ type: 'post', url: "ajax.php", data: { file: $('#file').val() //重いデータ(base64encodeした画像等) }, dataType: 'json', cache: false, async: true, xhr : function() { XHR = $.ajaxSettings.xhr(); if(XHR.upload) { XHR.upload.addEventListener('progress',function(e) { var percent = parseInt(e.loaded / e.total * 10000) /100; console.log(percent + "%"); $('#progress').text(percent + "%"); }, false); } return XHR; }, beforeSend: function(XMLHttpRequest){ }, success: function(e, textStatus){ console.log(e); }, error: function(XMLHttpRequest, textStatus, errorThrown){ console.log(XMLHttpRequest); }, complete: function(XMLHttpRequest, textStatus){ }, });
参考:http://takuya-1st.hatenablog.jp/entry/20121101/1351754417