TOP ▲
itcore TOP
> TIPS
> ajax_source.php
タグ:ajax javascript ソース ajax サンプルソース | itcore 2021年
ajax サンプルソース
<html>
<title>ajaxテストページ 2021-07-15</title>
<h1>ajax テストページ 2021-07-15</h1>
<h2>コマンド</h2>
<input type="button" id="sub_get" value="GET">
<input type="button" id="sub_post" value="POST">
<h2>結果</h2>
<div id="result"></div>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script>
$(function(){
$('#sub_get').click(function(){ u_ajax('GET'); });
$('#sub_post').click(function(){ u_ajax('POST'); });
});
function u_ajax(method) {
const date1 = new Date();
const id = 1;
const url = 'https://xxx';
param = {
url: url,
type: method,
// カスタムヘッダのCORS対応はうまくいってない。
//headers: {
//'Access-Control-Request-Headers' : 'X-Api-Key',
//'Access-Control-Allow-Origin':'*',
//'X-Api-Key' : 'xxx',
//},
}
if ('GET' == method) {
param.url += '?id=' + id;
} else if ('POST' == method) {
param.dataType = 'json';
data = {};
data.id = id;
param.data = JSON.stringify(data);
}
console.log('INFO44', method, param);
$.ajax(param)
.done(function(data, textStatus, jqXHR){
$('#result').text(method + ' ' + date1.toLocaleString());
$('#result').append('<br>done status=' + jqXHR.status);
$('#result').append('<br><pre>data=' + JSON.stringify(data, null, 2) + '</pre>');
console.log('INFO50', data)
}).fail(function(jqXHR, textStatus, errorThrown ){
$('#result').text(method + ' ' + date1.toLocaleString());
$('#result').append('<br>fail status=' + jqXHR.status);
$('#result').append('<br><pre>data=' + JSON.stringify(jqXHR.responseJSON, null , 2) + '</pre>');
console.log('INFO55', jqXHR);
});
}
</script>
</html>