【问题标题】:jquery ajax POST but PHP seeing GET?jquery ajax POST 但 PHP 看到 GET?
【发布时间】:2013-03-03 17:01:32
【问题描述】:

我正在使用 jQuery/Ajax 发送一些数据。我的代码被标记为 POST,但 PHP 实际上将其视为 GET。什么给了?

$.ajax({
         url: url,
         type: "POST",
         contentType: "application/json; charset=utf-8",
         dataType: "json",
         success: function (results) {
               callback(results);
         },
         error: function (req, msg, obj) {
               console.log('An error occured while executing a request for: ' + url);
               console.log('Error: ' + msg);
         }
});

我可以通过 print_r($_GET) 和 print_r($_POST) 确认它作为 GET 进入 PHP 端

【问题讨论】:

  • 这不是跨域请求吧?
  • 检查您的浏览器控制台以查看实际发送的内容
  • 没有。它来自 Spotify/local-machine 并访问远程 API
  • 啊,我将我的网址设置为website.com/api/?var1=data&var2=test...我知道现在是什么问题
  • @Tieson - URL 中的/deletepost/2 将在 PHP 服务器端的 GET 中进行解释。是的,它是有效的,但不,它不是 POST。

标签: php jquery ajax


【解决方案1】:

您没有在帖子中发送任何数据。尝试添加一些数据并检查服务器端。

JS

<script>
  $.ajax({
    url: url,
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data    : {
      'sample' : 'sample_data' 
    },
    success: function (results) {
      callback(results);
    },
    error: function (req, msg, obj) {
      console.log('An error occured while executing a request for: ' + url);
      console.log('Error: ' + msg);
    }
  });
</script>

PHP

<?php

$sample = '';

if (isset($_POST['sample'])) {
  $sample = $_POST['sample'];
}

echo $sample;

?>

// 输出

sample_data

【讨论】:

    【解决方案2】:

    我认为,如果你想发布尝试,则通过 url 传递值而不是 get

    $.ajax({
         url: url,
         type: "POST",
         data:{'my_var':'gautam'},
         -------------
    

    在php中你可以使用like

    <?php
        print_r($_POST);    //or you can print_r($_POST['my_var']);
    ?>
    

    给你'gautam'...

    【讨论】:

      【解决方案3】:

      使用$_SERVER['REQUEST_METHOD']检查它是GET还是POST

      echo $_SERVER['REQUEST_METHOD'];
      

      【讨论】:

        【解决方案4】:

        使用 $_REQUEST[] 获取 POST 和 GET 方法值

        <?php
          print_r($_REQUEST);
          extract($_REQUEST);
          echo "sample : ".$sample;
        
        ?>
        

        输出: 样本:样本数据

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-29
        • 1970-01-01
        • 2014-03-17
        • 2019-01-22
        • 1970-01-01
        • 2016-05-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多