首页 > 解决方案 > 将数据插入数据库后无法从 API 获取值

问题描述

我为 Web 留言板应用程序创建了一个 api。当我点击提交时,数据被插入到数据库中,然后在页面中显示结果列表。为什么我无法在页面上获取创建时间?如果我想获得创建时间,我必须按重新加载页面,创建时间会显示在页面上。API有什么部分需要修改吗?谢谢!

const siteKey = 'oscar';
const loadMorebtn = "<button class='load_btn btn'>Load More</button>";
const msgSection = $('.msg_section');
let lastId = null;
let isEnd = false;

function encodeHTML(input) {
  return input.replace(/\&/g, '&amp;')
    .replace(/\</g, '&lt;')
    .replace(/\>/g, '&gt;')
    .replace(/\"/g, '&quot;')
    .replace(/\'/g, '&#x27;')
    .replace(/\//g, '&#x2F;')
}

function appendMsgToDOM(container, msg, isPrepend) {
  const htmlContent = `
    <div class="card mt-4">
      <div class="card-body d-flex flex-column">
        <h5 class="card-title">${encodeHTML(msg.nickname)}</h5>
        <p class="card-text">${encodeHTML(msg.content)}</p>
        <p class="card_created_time align-self-end">${msg.created_at}</p>
      </div>
    </div>
  `
  if (isPrepend) {
    container.prepend(htmlContent);
  } else {
    container.append(htmlContent);
  }
}

// Only for get message
function getMsgsAPI(siteKey, before, cb) {
  let url = `http://localhost/w12/hw1/api_message.php?site_key=${siteKey}`;
  if (before) {
    url += '&before=' + before
  }
  $.ajax({
    url,
  }).done((data) => {
    cb(data);
  })
}

function getMsgs() {
  $('.load_btn').hide();
  if (isEnd) return;
  getMsgsAPI(siteKey, lastId, (data) => {
    if (!data.result) {
      alert(data.message);
      return;
    }
    const messages = data.messages;
    for (let msg of messages) {
      appendMsgToDOM(msgSection, msg)
    }

    if (messages.length === 0) {
      isEnd = true
    } else {
      lastId = messages[messages.length - 1].id;
      msgSection.append(loadMorebtn)
    }
  })
}

$(document).ready(() => {
  getMsgs();
  msgSection.on('click', '.load_btn', () => {
    getMsgs();
  })

  $('.add_msg_form').submit((e) => {
    e.preventDefault();
    const newMsgData = {
      'site_key': 'Oscar',
      'nickname': $('input[name=nickname]').val(),
      'content': $('textarea[name=content]').val()
    };

    $.ajax({
      type: 'POST',
      url: 'http://localhost/w12/hw1/api_add_message.php',
      data: newMsgData
    }).done(function (data) {
      if (!data.result) {
        alert(data.message);
        return;
      }
      $('input[name=nickname]').val('');
      $('textarea[name=content]').val('');
      appendMsgToDOM(msgSection, newMsgData, true);
    })
  });
})

用于显示数据的 API

<?php
  require_once('./conn.php');

  // Make sure the format of response is json
  header('Content-type:application/json;charset=utf-8');
  // CORS
  header('Access-Control-Allow-Origin: *');

  if(empty($_GET['site_key'])) {
    $json = array(
      'result'=>false,
      'message'=>'Please input the site_key in URL'
    );
    // covert the response to json format
    $response = json_encode($json);
    echo $response;
    die();
  } 

  $site_key = $_GET['site_key'];

  $sql = "SELECT * FROM oscar_msgboard WHERE site_key = ? " .
    (empty($_GET['before'])? '':'and id < ?') .
    " ORDER BY id DESC LIMIT 5";
  $stmt = $conn->prepare($sql);
  if(empty($_GET['before'])) {
    $stmt->bind_param('s', $site_key);
  } else {
    $stmt->bind_param('si', $site_key, $_GET['before']);
  }
  $result = $stmt->execute();
  if(!$result) {
    $json = array(
      'result'=>false,
      'message'=>'fail to connect to the server'
    );
    // covert the response to json format
    $response = json_encode($json);
    echo $response;
    die();
  }

  $result = $stmt->get_result();
  $messages = array();
  while($row = $result->fetch_assoc()) {
    array_push($messages, array(
      'id'=>$row['id'],
      'nickname'=>$row['nickname'],
      'content'=>$row['content'],
      'created_at'=>$row['created_at']
    ));
  }
  $json = array(
      'result'=>true,
      'messages'=>$messages
    );
    $response = json_encode($json);
    echo $response;
?>

插入数据的API

<?php
  require_once('./conn.php');

  // Make sure the representation of response is json
  header('Content-type:application/json;charset=utf-8');
  header('Access-Control-Allow-Origin: *');

  if(empty($_POST['nickname'])|| empty($_POST['site_key']) || empty($_POST['content'])) {
    $json = array(
      'result'=>false,
      'message'=>'Please input a message'
    );
    // covert the response to json format
    $response = json_encode($json);
    echo $response;
    die();
  } 

  $nickname = $_POST['nickname'];
  $site_key = $_POST['site_key'];
  $content = $_POST['content'];

  $sql = "INSERT into oscar_msgboard (site_key, nickname, content) values (?, ?, ?)";
  $stmt = $conn->prepare($sql);
  $stmt->bind_param('sss', $site_key, $nickname, $content);
  $result = $stmt->execute();
  if(!$result) {
    $json = array(
      'result'=>false,
      'message'=>'fail to connect to the server'
    );
    // covert the response to json format
    $response = json_encode($json);
    echo $response;
    die();
  }

  $json = array(
      'result'=>true,
      'message'=>'Success!'
    );
  
  $response = json_encode($json);
  echo $response;
?>

标签: javascriptphpapi

解决方案


推荐阅读