【问题标题】:Get AJAX POST Using PHP使用 PHP 获取 AJAX POST
【发布时间】:2019-03-06 16:26:12
【问题描述】:

我在表单中有一个drpcategory 下拉菜单。我将在下面粘贴下拉代码;

<div class="form-group">
     <label>Category</label>
     <select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
     <?php
          $category = ''.$dir.'/template/post/category.txt';
          $category = file($category, FILE_IGNORE_NEW_LINES);

          foreach($category as $category)
          {
              echo "<option value='".$category."'>$category</option>";
          }
     ?>
     </select>
</div>

然后我每次在上面的drpcategory 下拉列表中进行选择时,我都会 AJAX post,如下所示;

<script>
$(function(){

$('#drpcategory').on('change',function()
{

$.ajax({
method: 'post',
data: $(this).serialize(),
success: function(result) {
console.log(result);
}
});

});    

});
</script>

这似乎目前正在工作,因为我每次制作时都会在 Chrome 浏览器 > Inspect > Network 选项卡中获得如下输出drpcategory 中的一个选择。这是截图;

问题是我如何在同一页面中使用 PHP 捕获此 AJAX post 数据并在同一页面中捕获 echo 它?到目前为止,我已经尝试过;

<?php 
  if(isset($_POST['drpcategory']))
  {
    echo 'POST Received';
  }
?>

我正在寻找仅结合使用 PHP、JQuery 和 AJAX 的解决方案。

这个问题后来在这里更新和回答AJAX POST & PHP POST In Same Page

【问题讨论】:

  • 您使用的是$(this).attr('post'),我想这应该是$(this).attr('method'),因为它类似于&lt;form action="..." method="POST"&gt;,而不是&lt;form action="..." post="..."&gt;。如果您实际上是POST,您的数据应该在$_POST 中(也可以使用网络选项卡验证这一点!)
  • @ccKep:表单已经是&lt;form method="POST"&gt;,我已将AJAX 部分更改为$(this).attr('method'),现在它只是网络选项卡中的http://example.com/?page=post。 PHP 仍然没有回显任何内容。
  • 能否请您在 ajax 调用上监控网络选项卡。
  • @Parvej Alam:已经做到了。不同情况下的所有network tab输出都贴在我的问答、cmets下面。
  • 此问题已更新。可以的话请参考。

标签: php jquery ajax


【解决方案1】:

首先,这一行 -> type: $(this).attr('post') 应该是 type: $(this).attr('method'), 。所以这将给出值 ** type:post** 和

据我了解,每当您从 drpcategory 中选择选项时,您都会要求发送 ajax。你为什么要为此提交整个表格。如果我在你那里,我应该按照以下方式解决这个问题

$("#drpcategory").change(function(){
e.preventDefault();
var drpcategory=$(this).val();
$.ajax({
   type: 'post',
   data: drpcategory,
   success: function(result) {
        console.log(result);
   }
});
});

在你的php端,你可以得到你的数据,

echo $_POST['drpcategory'];

【讨论】:

  • 为什么$("#drpcategory").change(function(); 函数有一个e.preventDefault();?但我在$('#form').submit(function(e) 中尝试过这段代码,PHP 没有回显任何内容。
  • 我只是用它来阻止默认功能。如果你愿意,你可以省略。试试这样,它会工作的。
  • 已经省略并尝试过,正如我所提到的。这个运气不好。
  • 它应该可以工作并且对我来说工作正常。请尝试将 id 名称从 drpcategory 更改为不同的名称,例如 drp。有时,ajax 会保留所有名称的缓存,并且类似的字符串可能指向 chrome 中的相同指针。试试这个
  • 尝试了不同的ids 并且再次没有回声。 PHP 是否需要重新加载页面才能捕获 POST 并显示回显?因为正如我在问题中提到的,目前它只会在页面使用标准提交方法重新加载页面重新加载时才会回显。如果是这样的话,那么我想这种 AJAX 方法对我不起作用。
【解决方案2】:

我建议你阅读 ajax 函数的文档,我尝试复制它,我必须解决这个问题:

$.ajax({
    // If you don't set the url
    // the request will be a GET to the same page
    url: 'YOU_URL',
    method: 'POST', // I replaced type by method
    data: $(this).serialize(),
    success: function(result) {
        console.log(result);
    }
});

http://api.jquery.com/jquery.ajax/

输出

【讨论】:

  • 我没有url,因为我要发布到同一页面。我已经尝试过$(this).attr('method')。在网络选项卡中,它只给出了http://example.com/?page=post 输出。 PHP 仍然没有回显任何内容。
  • 如果您发布到同一页面,这意味着您发布到该页面的 url。当你做一个普​​通的 html 帖子时,如果你没有指定一个 url,你的浏览器会为你填写。
  • 没错,如果你不放 URL 请求会是同一个页面,我建议你声明 url 来测试它,你可以看看它是如何工作的。
  • @roag92 我的网页结构从http://example.com/index.php开始。现在我在http://example.com/index.php?page=post,用户可以在这里发布新内容。我有点困惑url 我需要在里面写什么,所以我删除了url 字段供浏览器读取。
  • 如果是同一个文件,您可以将 url 设置为 http://example.com/index.php 或仅设置为 index.php。有关相对 url 的更多信息,请查看stackoverflow.com/questions/4765740/…
【解决方案3】:
First change to $value

<div class="form-group">
 <label>Category</label>
 <select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
 <?php
      $category = ''.$dir.'/template/post/category.txt';
      $category2 = file($category, FILE_IGNORE_NEW_LINES);

      foreach($category2 as $value)
      {
          echo "<option value='".$value."'>".$value."</option>";
      }
 ?>
 </select>

然后添加网址

<script>
 $(function()
 {
   $('#form').submit(function(e)
   { 
      e.preventDefault();
      $.ajax({
          url:'folder/filename.php',
          type: 'post',
          data: '{ID:" . $Row[0] . "}',
          success: function(result) {
              console.log(result);
          }
      });
   });
   $('#drpcategory').on('change',function()
   {
      $("#form").submit();
   });
 });

尝试请求

if(isset($_REQUEST['ID']))

结果将/应该发送回同一页面

【讨论】:

  • 没关系。我知道使用相同的变量名并不理想。但这里真正的问题是 PHP 没有正确获取 AJAX POST?
  • 尝试了您编辑的解决方案。请注意,我使用 AJAX 发布到同一页面,所以没有 url。但是我已经在同一页面上使用url 进行了尝试,但仍然没有来自 PHP 的回显。
  • 此问题已更新。可以的话请参考。
【解决方案4】:

请试试这个代码:

$.post('URL', $("#FORM_ID").serialize(), function (data)
{
  alert('df);
}

【讨论】:

  • 什么是df?我只是像$.post('', $('#form').serialize(), function (data){alert(data);}); 一样编辑了它,它只是给了我一个警报窗口,其中包含我当前所在的整个页面的源代码。
  • 此问题已更新。可以的话请参考。
【解决方案5】:

我认为您在 ajax jQuery resquest 中存在错误语法错误,因为 ajax post 'http://example.com/?page=post&drpcategory=Vehicles' 不会在浏览器网络选项卡中返回此类型的 url。

<?php var_dump($_POST); exit; ?> please do this statment in your php function if anything posted to php page it will dump.

这里是ajax请求示例

$("#drpcategory").change(function(){

e.preventDefault();

var drpcategory=$(this).val();

$.ajax({

类型:'发布',

数据:drpcategory,

成功:函数(结果){

    console.log(result);

}

});

});

`

【讨论】:

  • 已按照此处答案的建议对问题进行了小幅更新。仍然没有运气。在浏览器的“网络”选项卡中,我收到了 http://example.com/?page=post 请求,而您的 PHP 已将 array(0) { } 转储为输出。
  • 有时 jquery 会显示这种类型的疯狂想法...是否认为打开新脚本标签创建 js 函数,在 html 中使用 onchnage="" 方法然后在 js 函数中编写 ajax
  • 我想继续使用 jQuery,因为我很难理解标准的 JS。即使我尝试过,我也可能会再次遇到这个问题。我怀疑 jQuery 是这里的问题,我遗漏了一些东西。
  • ya JQuery 是问题所在!使用 std.JS.nothing 很难 html :
  • 使用您的代码并在“网络”选项卡中获得与以前相同的活动,但仍然没有显示 PHP 转储。基本上还是一样的。
【解决方案6】:

听起来您正在尝试同时解决几件事。在我开始直接的问题之前,我们需要进行一些基础工作,以便您了解需要发生的事情。

首先,关于 URL 的混淆:

您正在通过 index.php 路由所有内容。因此,index.php 需要遵循如下结构:

<?php 
// cleanse any incoming post and get variables

// if all your POST requests are being routed to this page, you will need to have a hidden variable 
// that identifies which page is submitting the post. 

// For this example, assume a variable called calling_page.  
// As per your naming, I'll assume it to be 'post'.

// Always check for submitted post variables and deal with them before doing anything else.
if($_POST['calling_page'] == 'post') {
  // set header type as json if you want to use json as transport (recommended) otherwise, just print_r($_POST);
  header('Content-Type: application/json');

  print json_encode(array('message' => 'Your submission was received'));
  
  // if this is from an ajax call, simply die.  
  // If from a regular form submission, do a redirect to /index.php?page=some_page
  die; 
}

// if you got here, there was no POST submission.  show the view, however you're routing it from the GET variable.
?>
<html>
  (snip)
  <body>
    <form id="form1" method="post">
      <input type="hidden" name="calling_page" value="page" />
      ... rest of form ...
      <button id="submit-button">Submit</button>
    </form>

}

现在,关于 JQuery 和 AJAX 的困惑:

根据https://api.jquery.com/jquery.post/,您必须提供一个 URL。

除了 url 之外的所有属性都是可选的

您的 JQuery AJAX 将向您的 index.php 页面发送一个发布请求。当您的页面如上所示执行时,它将简单地打印{message: "Your submission was received"},然后死掉。 JQuery 将等待该响应,然后执行您告诉它执行的任何操作(在此示例中,将其打印到控制台)。


讨论后更新

<div class="form-group">
     <label>Category</label>
     <select class="form-control bg-dark btn-dark text-white" id="drpcategory" name="drpcategory" required>
     <?php
          $category = ''.$dir.'/template/post/category.txt';
          $category = file($category, FILE_IGNORE_NEW_LINES);

          foreach($category as $category)
          {
              echo "<option value='".$category."'>$category</option>";
          }
     ?>
     </select>
</div>

<!-- HTML to receive AJAX values -->
<div>
  <label>Item</label>
  <select class="" id="drpitem" name="drpitem"></select>
</div>





<script>
  $(function(){

    $('#drpcategory').on('change',function() {
      $.ajax({
        url: '/receive.php',
        method: 'post',
        data: $(this).serialize(),
        success: function(result) {
          workWithResponse(result);
        }
      });

    });    

  });


  function workWithResponse(result) {

    // jquery automatically converts the json into an object.
    // iterate through results and append to the target element

    $("#drpitem option").remove();
    $.each(result, function(key, value) {   
         $('#drpitem')
             .append($("<option></option>")
                        .attr("value",key)
                        .text(value)); 
    });        
          }

</script>

receive.php:

<?php 
// there can be no output before this tag.

if(isset($_POST['drpcategory']))
{
  // get your items from drpcategory.  I will assume: 
  $items = array('val1' => 'option1','val2' => 'option2','val3' => 'option3');

  // send this as json.  you could send it as html, but this is more flexible.
  header('Content-Type: application/json');

  // convert array to json
  $out = json_encode($items);

  // simply print the output and die.
  die($out);


}

一切正常后,您可以从receive.php 获取代码,将其粘贴在index.php 的顶部,然后将ajax 调用重新指向index.php。确保在此代码 sn-p 之前没有输出可能。

【讨论】:

  • 好的,所以如果 AJAX 专门用于允许将信息发送回服务器而不需要刷新页面,并且在我的问题中,如果 PHP 仅使用标准提交功能和页面重新加载成功回显,为什么当相同的标准提交函数被 AJAX 覆盖时,PHP 无法回显?是不是因为 PHP 没有重新加载页面来显示更改?
  • html提交和AJAX提交都发送相同的POST信息。唯一的区别是 AJAX 在幕后进行而不重写页面。为了对其进行故障排除,您需要打开开发人员工具并查看网络选项卡。提交后,您将看到文件请求。点击它,你可以看到提交的内容和回复的内容。
  • 但是,如果页面重新加载,那么您知道您实际上并没有使用 ajax 提交。然后回到文档看看你错过了什么。
  • 我只是使用默认提交来检查 PHP 是否在此处回显。我实际上已经覆盖了问题中提到的默认提交,现在仍然如此。它是使用 AJAX 提交的,并且没有页面重新加载。每次我在drpcategory 中进行更改时,我都会在网络选项卡中以http://example.com/?page=post 收到文件请求。所以我可以确定提交是使用 AJAX 发送的,我只是想不通为什么 PHP 不是 echo ,而默认提交确实在页面中显示了 PHP echo
  • 您希望它在哪里以及如何回响?正如所写,它不会显示在页面上,只会显示在控制台中。要进行故障排除,需要知道服务器在响应什么,通过点击文件请求找到。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多