Authentication




Cancel OK
B!コメントする  2016-12-10 02:13:00 by admin

超シンプルなチャット作ってみた

ajax的なやり取りするヤツってよく使うけど毎回探してる気がするので置いておきます。

<?php
// 書き込み
if( filter_input(INPUT_POST, 'send_val') ){
    // Data追記
    file_put_contents('db.txt',filter_input(INPUT_POST, 'send_id', FILTER_SANITIZE_SPECIAL_CHARS) . "\t" . filter_input(INPUT_POST, 'send_val', FILTER_SANITIZE_SPECIAL_CHARS) . "\n", FILE_APPEND);
    $result = array('completely' => 'completely');
    $json = json_encode($result);
    header('Content-Type: application/json');
    echo $json;
    exit;
// 読み込み
}elseif( filter_input(INPUT_POST, 'get_val') ){
    // Data読取り
    $get_db = preg_replace('/\n|\r/', '<hr>', file_get_contents('db.txt'));
    $result = array('completely' => 'completely', 'get_db' => $get_db);
    $json = json_encode($result);
    header('Content-Type: application/json');
    echo $json;
    exit;
}
?>
<html lang="ja">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>api</title>

    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>

<div class="get_db"></div>

<input type="text" id="send_id"><input type="text" id="send_val">
<button type="button" id="send">send</button>

<script>

    /* データ送信 */
    $('#send').click(function(){
        var send_id    = $("#send_id").val();
        var send_val    = $("#send_val").val();

        // Data を送信
        $.ajax('chat.php', {
            method: 'POST',
            dataType: 'json',
            timeout:4000,
            data: {'send_id': send_id, 'send_val': send_val},
            error: function() {
                alert("TimeOut!");
            },
            success: function(data, textStatus, jqXHR) {
                if( data['completely'] == 'completely' ) {
                    /* alert('Seccess'); */
                    /* window.location = data['completely_location']; */
                }
            }
        });
        // false を返してデフォルトの動作をキャンセル
        return false;
    });
    /* データ定期取得 */
    var timer_id = setInterval( function () {
        $.ajax('chat.php', {
            method: 'POST',
            dataType: 'json',
            timeout:4000,
            data: {'get_val': 'get_val'},
            error: function() {
                alert("TimeOut!");
            },
            success: function(data, textStatus, jqXHR) {
                if( data['completely'] == 'completely' ) {
                    var obj = data['get_db'];
                    $('.get_db').html(obj);
                }
            }
        });
    } , 4000 );
</script>

</body>
</html>

シンプルです。
非同期でデータ取りに行って更新します。
投稿してもリロードなどは発生しません。
何かと使えるので便利ですが毎回探すのも面倒なので自分の為に置いておきます。


jQuery 開発 自分用  

  • コメント
  • コメントはまだありません