猿问

为什么PHP收不到AJAX发出的post请求

这是我的javascript代码,成功事件被执行。但是 post 数组在 php 文件中保持为空。


    document.querySelector(".postButtons").addEventListener("click",(e)=>{

    const postID = e.target.value;

    if(e.target.id == "edit"){

        //Send post request to edit the post

        $.ajax({

            type: 'POST',

            url: '../edit.php',

            data: {postID : postID},

            contentType: 'application/json; charset=utf-8',

            data: 'json',

            cache: false,

            success: function(response) {

                window.location.href="../edit.php"

            },

            error: function(err){

                console.log(err)

            }

        })

    }else if(e.target.id == "del"){

        //Send post request to delete the post

    }

})


  <?php

if(isset($_POST["postID"])){

    echo $_POST["postID"];

?>

我试图在javascript中将变量记录到控制台,它似乎工作。当我试图返回它时,状态码是200。


杨__羊羊
浏览 157回答 1
1回答

回首忆惘然

window.location.href 执行常规 GET 请求。因此,您在页面上看不到 postID。您可以在请求中的控制台中看到 postID但是如果你想在页面重新加载时看到 postID,那么你需要使用表单发送这个请求,而不是 ajax。<form action="../edit.php" method="POST" id="sendForm">&nbsp; &nbsp; <input type="hidden" name="postID" id="postID">&nbsp; &nbsp; <input type="submit"></form>if(e.target.id == "edit"){&nbsp; &nbsp; $('#postID').val(postID);&nbsp; &nbsp; $('#sendForm').submit();}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答