Ajax和PHP,发布请求无效

时间:2018-01-25 02:45:08

标签: javascript php jquery json ajax

所以我试图使用jquery / ajax将一些PHP文件中的一些数据发布到另一个PHP文件中。下面的代码显示了一个函数,它接受来自单击的特定div的数据,并尝试对我要发送到的PHP文件发出ajax post请求。

 $(function (){
              $(".commit").on('click',function(){
                const sha_id = $(this).data("sha");
                const sha_obj = JSON.stringify({"sha": sha_id});
                $.ajax({
                   url:'commitInfo.php',
                   type:'POST',
                   data: sha_obj,
                   dataType: 'application/json',
                   success:function(response){
                      console.log(response);
                      window.location.replace("commitInfo");
                    },
                   error: function (resp, xhr, ajaxOptions, thrownError) {
                        console.log(resp);
                     }
                 });
              });
           });

然后在另一个php文件'commitInfo.php'内部我尝试使用以下代码获取/打印数据:

$sha_data = $_POST['sha'];
echo $sha_data;
print_r($_POST);

然而,没有任何作用。我没有打印输出,$ _POST数组是空的。可能是因为我在点击时将页面视图更改为commitInfo.php页面,并且在发布数据之前它将转到页面? (一些奇怪的异步问题?)。或者是其他东西?我尝试过多种变化,但没有真正有用。我尝试使用'method'而不是'type',我尝试发送dataType'text'而不是'json'。我真的不知道问题是什么。 另外,我在我的本地mac上使用'sudo apachectl start'运行我的apache服务器,并在浏览器中以'http://localhost/kanopy/kanopy.php'&& 'http://localhost/kanopy/commitInfo.php'。

此外,当我将其作为dataType'text'发送时,成功函数会运行,但我收到NO数据。当我将其作为dataType'json'发送时,它会出错。不知道为什么。

如果有人可以提供帮助,那就太棒了!

1 个答案:

答案 0 :(得分:3)

您不需要JSON.stringify,您需要将数据作为JSON对象传递:

$(function() {
  $(".commit").on('click', function() {
    const sha_id = $(this).data("sha");
    const sha_obj = {
      "sha": sha_id
    };
    $.ajax({
      url: 'commitInfo.php',
      type: 'POST',
      data: sha_obj,
      dataType: 'json',
      success: function(response) {
        console.log(response);
      },
      error: function(resp, xhr, ajaxOptions, thrownError) {
        console.log(resp);
      }
    });
  });
});

commitInfo.php上,您必须echo格式json字符串

=====================================

如果您想重定向到commitInfo.php,您可以:

$(".commit").on('click',function(){ 
   const sha_id = $(this).data("sha"); 
   window.location.replace("commitInfo.php?sha=" + sha_id ); 
});