【问题标题】:Problem with php handling ajax in the same filephp在同一个文件中处理ajax的问题
【发布时间】:2019-10-02 07:55:08
【问题描述】:

我有一个严重的问题,我无法在php中接收ajax发送的数据。我已经阅读了很多关于此的教程,但仍然没有解决。所以,如果你们有神奇的解决方案,那会让我很开心。 这是代码,注意它在同一个文件problem.php中assocStored 是一个数组或对象如果我在 jvascript 上检查它,它就有正确的数据

window.onload = function(e){
        var assocStored = JSON.parse(localStorage.getItem("associes"));

        $.ajax({
                type : "POST",
                data : {"problem" : assocStored},
                success : function(res){
                    console.log("action performed successfully");
                }
        })
    }
<div>
    <h3>php</h3>
    <?php
         var_dump ($_POST);
         if( isset($_POST['problem']) ){
            foreach ($_POST['problem'] as $associe) {
            echo($associe["sex"]." ".$associe["firstname"]." ".$associe["lastname"]);
            }
            exit;
         }
    ?>
</div>

【问题讨论】:

  • 您可以在网络标签中查看发送请求,并确保它发送正确的数据,而不是通过js。
  • 是的,它确实在我的浏览器的本地存储中,名为 asocies
  • 我在下面发表了评论。所以我的意思是检查您的发送请求,如方法、参数、数据类型等......

标签: html ajax local-storage


【解决方案1】:

正如我上面的评论,我猜你的请求发送了一个 GET 方法。

在您的代码中,您使用的typePOST,但typemethod 的别名。如果您使用的是 1.9.0 之前的 jQuery 版本,则应该使用 type

所以你可以将你的ajax 修改到这里:

$.ajax({
    method: "POST",
    data : { "problem" : JSON.stringify(assocStored) }, // convert to json
    dataType: "json", // add type
    success : function(res){
        console.log("action performed successfully");
    }
})

如果仍然无法正常工作,请将此代码添加到 ajax:

$.ajax({
    method: "POST",
    data : { "problem" : JSON.stringify(assocStored) }, // convert to json
    dataType: "json", // add type
    beforeSend: function(req) {
        if (req && req.overrideMimeType) {
            req.overrideMimeType("application/j-son;charset=UTF-8");
        }
    },
    success : function(res){
        console.log("action performed successfully");
    }
})

我希望它有效。

【讨论】:

  • 不,它没有。
  • 对不起,我忘了assocStored 是一个数组,请再次检查我的答案,希望它有效。
  • 哦,试试data : JSON.stringify({ "problem" : assocStored }),
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
相关资源
最近更新 更多