Jquery POST请求到另一个PHP文件不起作用

时间:2018-01-20 09:39:38

标签: php jquery ajax

我正在尝试发布一个帖子请求,将一些数据从一个php文件发送到另一个。我正在使用Jquery,我的代码如下所示

我的帖子文件:

$(function (){
    $(".commit").click(function(){
        const sha_id = $(this).data("sha");
        $.ajax({
            url : 'commitInfo.php',
            type : 'POST',
            data : sha_id,
            contentType: "application/json; charset=utf-8",
            success: function(response){
                console.log(sha_id);
                window.location.replace("commitInfo");
            }
        });    
    });
});

我收到的文件:

var_dump($_POST);

$_POST返回一个空数组。并且还尝试将我的数据放在对象中。也不起作用。谁知道出了什么问题?

3 个答案:

答案 0 :(得分:0)

在将ajax请求发送到服务器之前,检查包含数据的变量,然后通过控制台将其发送到浏览器。 Ajax请求将数据转换为键值对或json格式,您需要将json对象发送到服务器以获取对数据的访问

$.ajax({
    url : 'whatever-folder/whatever-url.php',
    type : 'POST',
    data : { anykey: anything },
    contentType: "application/json; charset=utf-8",
    success: function(response){
         console.log(response);
    }
});

您将收到服务器中的帖子。

答案 1 :(得分:0)

您是否尝试过使用FormData see

$(function (){
    $(".commit").click(function(){
        const sha_id = $(this).data("sha");
        var data = new FormData();
        data.append('id',sha_id );
        $.ajax({
            url : 'commitInfo.php',
            type : 'POST',
            data : data,
            processData: false,
            contentType: false,
            success: function(response){
                 console.log(sha_id);
                 window.location.replace("commitInfo");
            }
        });
     });
 });

答案 2 :(得分:0)

(1.). post file:

$(function (){
    $(".commit").click(function(){
        const sha_id = $(this).data("sha");
        $.ajax({
            url : 'commitInfo.php',
            type : 'POST',
            dataType: 'json',
            data : sha_id,
            contentType: "application/json; charset=utf-8",
            success: function(response){
                console.log(sha_id);
                window.location.replace("commitInfo");
            }
        });    
    });
});




(2.). Json data does not receive in post.

$json = file_get_contents('php://input');
$post = json_decode($json, TRUE);

echo '<pre>';
var_dump($post);
echo '</pre>';
相关问题