私は、Ajax、jQuery、および PHP をいじって、それらの組み合わせと、それらがどのように相互に統合されるかに慣れようとしています。これが私の最初の試みです。これは、ajaxがリクエストとレスポンスをどのように処理するかを確認しようとするだけで、特別なことは何もしない非常に単純なフォーム送信です。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<title>My 1st AJAX attempt</title>
<link href="http://www.ht-webcreations.com/test/styles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#wait').hide();
$("#emailContactus").submit(function(){
$('#wait').show(),
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'includes/ajax.php?action=emailContactus',
success: function(data) {
console.log("Success posting emailContactus"),
$('#wait').hide(),
$('#notifications').html(data).addClass('ajaxsuccess').show();
},
error: function (xhr, textStatus, errorThrown) {
console.log("Success posting emailContactus: "+ textStatus, errorThrown);
},
complete: function(data){
$('#wait').hide(),
$('#notifications').html(data).addClass('ajaxsuccess').show();
}
});
return false;
});
});
</script>
</head>
<body>
<div id="wait"><img src="http://www.ht-webcreations.com/test/loading_ajax.gif" width="80" height="80"></div>
<div id="notifications"></div>
<form name="emailContactus" id="emailContactus" method="post">
<table width="500" border="0" align="center" cellpadding="5" cellspacing="0">
<tr>
<td>name</td>
<td><label for="name"></label>
<input type="text" name="name" id="name"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="button" id="button" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
ajax.php:
<?
///////////////// AJAX REQUESTS /////////////////
switch($_REQUEST['action']){
case('emailContactus'): if($_POST['name']=='a') { echo $value = 'User is A'; } else { echo $value = 'User is NOT A'; }
break;
case('addContact'): echo 'Contact added!';
break;
default: break;
}
?>
この単純な例(動作中のデモはこちら)の問題は、データ応答が #notifications div に追加されることを期待していますが、HTML が読み込まれる前であっても、ドキュメントの一番上に出力されていることです。見て、変更する必要があるものを提案してください。また、最初から正しい方向性を示していただきたいので、私のコードに関するすべてのコメントをお待ちしております。ありがとう!