【问题标题】:POST data sent with ajax doesn't trigger ($_SERVER["REQUEST_METHOD"] == "POST") in 2nd PHP File使用 ajax 发送的 POST 数据不会在第二个 PHP 文件中触发 ($_SERVER["REQUEST_METHOD"] == "POST")
【发布时间】:2017-06-22 11:55:51
【问题描述】:

我正在尝试进行某种简单的文字聊天。

我有两个 PHP 文件(index.phpsend.php)和一个 javascript 脚本(script.js)。

index.php,我得到了以下表格:

<form id="formSend" method="post">
  <input id="inputMsg" class="form-control input-msg" type="text" name="msg" autocomplete="off">
  <button id="btnSend" class="btn btn-success button-send" type="submit" name="send">Send</button>
</form>

为了防止页面重新加载,数据是通过我的 javascript 文件中的 ajax 请求发送的:

$('#formSend').submit(function(e){
  e.preventDefault();
  var url="send.php";
  var posting = $.post(url, {msg: $('#input-msg').val() });
  posting.done(function(data){
    $('#inputMsg').val('');
    console.log('success');
  });
});

ajax 请求有效(成功记录在控制台中),但在send.php 什么都没有发生。

我在send.php 中使用以下代码:

if ($_SERVER["REQUEST_METHOD"] == "POST"){
  if(isset($_POST['msg']) && !empty(trim($_POST['msg']))){
    $msg = htmlspecialchars(trim($_POST["msg"]));
    $check = true;
  }
  else{
    $check = false;
  }

  if ($check = true) {
    $query = "INSERT INTO chat(message) values (?)";
    $stmt = $mysqli->prepare($query);
    if($stmt===false){
      $error = 'Database error';
    }
    if(!$stmt->bind_param('s', $msg)){
      $error = 'Database error';
    }
    if(!$stmt->execute()){
      $error = 'Database error' . $mysqli->error;
    }
    if(empty($error)){
      $mysqli->close();
      $success = 'Success';
    }
  }
}

我错过了什么吗?我真的不知道为什么它不起作用...

【问题讨论】:

  • 也许您应该输出 $error/$success 变量的内容,看看实际发生了什么……?
  • 不用加if ($_SERVER["REQUEST_METHOD"] == "POST")试试吧
  • if ($_SERVER['REQUEST_METHOD'] === 'POST') { // 请求使用的是 POST 方法 }
  • if($check = true) 应为 if($check)if($check == true)
  • 当您对该脚本发出的请求是 AJAX 请求时,在这里使用 iframe 有什么意义……?这到底是什么意思——你是不是把&lt;iframe src="send.php"&gt;&lt;/iframe&gt;放到你的页面上?那么当然你的 if 条件不会为真,因为浏览器会发出一个很好的旧 GET 请求来加载要在 iframe 中显示的文档。

标签: php jquery ajax post


【解决方案1】:
<input id="inputMsg" class="form-contr .... >

还有

var posting = $.post(url, {msg: $('#input-msg').val() });

不匹配。

删除- 并大写M

【讨论】:

  • 很抱歉在聊天中浪费了您的时间,再次感谢您的耐心等待:)
  • 唯一遗憾的是我没能早点发现它。至少,我希望你学会了如何诊断脚本,这样以后就不会再发生这样的事情了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-09-29
  • 1970-01-01
  • 2016-02-05
  • 2010-11-09
  • 2014-04-01
  • 2011-02-21
  • 1970-01-01
相关资源
最近更新 更多