自宅のPCにApacheを設定しています。
- ajax.htmlというページには、ボタンに xmlhttp リクエストが設定されています。(同じディレクトリにある HTML ページmain.htmlをフェッチするため)
- ボタンをクリックしても何も起こらず、応答をテキストとして設定しました。
- 以下はJavaScriptコードです。
function()
{ var httpRequest; document.getElementById("ajaxButton").onclick = function() { makeRequest('main.html'); };function makeRequest(url) { if (window.XMLHttpRequest) { httpRequest = new XMLHttpRequest(); } else if (window.ActiveXObject) { try { httpRequest = new ActiveXObject("Msxml2.XMLHTTP"); }
catch (e) { try { httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }
catch (e) {} } }if (!httpRequest) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } httpRequest.onreadystatechange = alertContents; httpRequest.open('GET', url); httpRequest.send(); }
function alertContents() { if (httpRequest.readyState === 4) { if (httpRequest.status === 200) { alert(httpRequest.responseText); } else { alert('There was a problem with the request.'); } } } })();
html コード;
<html>
<head>
<title>Ajax Demo</title>
</head>
<body>
<input type="button" id="ajaxButton" value="Click" />
<script type="text/javascript" src="ajax.js">
</script>
</body>
</html>