与api和txt文件的简单聊天

时间:2019-02-26 18:37:03

标签: javascript php api chat

我正在建立两个用户之间的简单聊天,我想在收件人的聊天中显示发件人的姓名,以便它像发件人一样显示在收件人的屏幕上:发件人向收件人的消息。

HTML表单:

<div id="lblMessages">
    </div>
    <form>
      <input name="txt-user-id" type="text" value="<?= $sUserId; ?>">
      <input name="txt-message" type="text">
      <button>send</button>
    </form>
  </div>

JS:

<script>

    let sUserId = '<?= $sUserId; ?>'

    $('form').submit( function(){
      $.ajax({
        method: "POST",
        url: "api-set-message.php",
        data: $('form').serialize(),
        cache: false
      }).
      done(function( sMessages ){
        console.log('done')
      }).
      fail(function(){

      })
      return false;
    })


    setInterval( function(){

      $.ajax({
        method: "GET",
        url: "api-get-messages.php?sUserId="+sUserId,
        cache: false
      }).
      done(function( sMessages ){
        $('#lblMessages').append('<div>'+sMessages+'</div>')
      }).
      fail(function(){

      })

    } , 1000 )

  </script>

API设置消息:

<?php
$sUserId = $_POST['txt-user-id'];
$sMessage = $_POST['txt-message'];
$sUserId = $sUserId == 'client' ? 'bank' : 'client';
file_put_contents( "to-$sUserId.txt", $sMessage );

API获取消息

<?php
$sUserId = $_GET['sUserId'];
$sMessages = file_get_contents("to-$sUserId.txt");
file_put_contents("to-$sUserId.txt", '');
echo $sMessages;

0 个答案:

没有答案