ajax時に設定するオプション、通信結果をまとめてみました。
$.getや$.postを使った時の通信結果
msg.php
<?php
echo $POST['msg'];
?>
sample.js
$.get('msg.php',{ msg: 'てすと'}, function(data, status, xhr){
console.log(this.url); //msg.php?msg=%E3%81%A6%E3%81%99%E3%81%A8
console.log(data); //てすとを表示
console.log(status); //success
console.log(xhr.status); //200
console.log(xhr.statusText); //OK
console.log(xhr.responseText); //てすとを表示
console.log(xhr.getAllResponseHeaders()); //すべてのレスポンスヘッダー
//個別にヘッダーを取得する場合
console.log(xhr.getResponseHeader("Date")); //Sun, 07 Dec 2014 15:20:04 GMT
console.log(xhr.getResponseHeader("Content-Type")); //text/html; charset=UTF-8
console.log(xhr.getResponseHeader("Content-Length")); //18
console.log(xhr.getResponseHeader("Last-Modified")); //12/07/2014 15:19:00
});
$.getや$.post時に「404 Not Found」等のエラーの場合、実行されないのでajaxSetupでエラー処理する必要があります。
sample.js
$.ajaxSetup({
error: function(xhr, status, error){
console.log(this.url); //msg.php?msg=%E3%81%A6%E3%81%99%E3%81%A8
console.log(status); //error
console.log(xhr.status); //404
console.log(error); //Not Found
}
});
$.ajaxを使った通信処理
sample.js
//fileタイプを送る場合はFormDataを使う
var fd = new FormData($('#mainform'));
fd.append("msg", "てすと");
fd.append("upimg", $('input[name=upimg]').prop('files')[0] );
$.ajax({
url: 'msg.php',
type: 'POST',
//data: fd, //fileタイプを送る場合にセット
data: {
msg: 'てすと'
},
//processData: false, //fileタイプを送る場合はfalse
//contentType: false, //fileタイプを送る場合はfalse
dataType: 'html', //text xml html script json jsonp
jsonp: 'jsoncallback', //dataTypeでjsonpを指定した場合
crossDomain: true, //クロスドメインの場合
timeout: 3000, //タイムアウト3秒
async: true, //非同期
cache : false, //キャッシュを残さない
username: 'myname', //HTTP認証が必要な場合
password: 'mypassword', //HTTP認証が必要な場合
beforeSend: function (xhr) { //リクエスト前に実行
console.log('ヘッダーをセットして送信!');
//xhr.setRequestHeader("content-type","application/x-www-form-urlencoded;charset=utf-8");
}
}).done(function(data, status, xhr){ //通信成功時の処理
console.log(data); //てすとを表示
console.log(status); //success
console.log(xhr.status); //200
console.log(xhr.statusText); //OK
console.log(xhr.responseText); //てすとを表示
$(document.body).append(data);
}).fail(function(xhr, status, errmsg) { //通信失敗時の処理
console.log(xhr.status); //404
console.log(status); //error
console.log(errmsg); //Not Found
}).always(function(arg1, status, arg2) { //通信が完了したら呼ばれる
console.log(this.url); //msg.php
//リクエストの結果によって引数のオブジェクトが変わるみたい
if(status == 'success'){
console.log(arg1); //てすとを表示
console.log(status); //success
console.log(arg2); //xhrオブジェクト
console.log(arg2.status); //200
}else if(status == 'error'){
console.log(arg1); //xhrオブジェクト
console.log(arg1.status); //404
console.log(status); //error
console.log(arg2); //Not Found
}
});
fileタイプを送る場合はformに「enctype="multipart/form-data"」を設定します。
ajaxにセットするパラメーターはFormDataとして送ります。
この時**「processData: false」、「contentType: false」**を設定します。
html
<form action="msg.php" method="post" enctype="multipart/form-data" id="mainform">
<input type="file" name="upimg">
</form>
PHP側ではmsgとfileがあれば表示します。
msg.php
echo $_POST['msg'] . 'を表示<br>';
if(isset($_FILES["upimg"]["tmp_name"])){
$fp = fopen($_FILES["upimg"]["tmp_name"], "r");
$contents = fread($fp, $_FILES["upimg"]["size"]);
fclose($fp);
echo '<img src="data:'. $_FILES['upimg']['type'] .';base64, ' . base64_encode($contents) . '" >';
}
簡単な処理は$.get、$.postを使い、重い処理は$.ajaxと使い分けるといいと思います。
注意点は、$.ajaxのときに、alwaysで受け取る引数が通信ステータスによって変わってしまうので気をつけてください。