使用Ajax将数据发送到本地PHP脚本,接收响应但是从不满足php文件中的if-condition

时间:2016-03-22 15:27:14

标签: php jquery ajax

我有一个可拖动的div容器,每当我删除它时,它的位置将发送到本地php脚本。

$(function() {
    $( "#fenster" ).draggable({
        stack: "#fenster", stop: function(event, ui){
            var pos_x = ui.offset.left;
            var pos_y = ui.offset.top;

            $.ajax({
                type: "POST",
                contentType: "application/json",
                data: {'x': pos_x},
                url: "index.php",
            }).done(function(msg){
                alert("data Saved: " + msg);
            });
        }
    });
});

在php文件(index.php)中,我检查是否设置了$ _POST [' x']。不幸的是,无论我做什么,都无法满足这一条件。

  if((isset($_POST['x']))){
    $_SESSION['xLoc'] = $_POST['x'];
    echo "Test";
  }

删除窗口后,我得到一个响应(msg显示输出的警告),根据FireBug,请求包含x。

2 个答案:

答案 0 :(得分:2)

PHP超全局$ _POST仅在您使用这些内容类型

时可用
    application/x-www-form-urlencoded (standard content type for simple form-posts) or
    multipart/form-data-encoded (mostly used for file uploads)

您正在使用application / json,这意味着您需要使用...

获取流
$rawData = file_get_contents("php://input");
$d = json_decode($rawData);
if((isset($d['x']))){
  $_SESSION['xLoc'] = $d['x'];
  echo "Test";
}

或者,如果你实际上不需要提交JSON,只需从你的jquery中删除contentType,你就可以使用你已经拥有的代码在php端检索$ _POST。

$.ajax({
    type: "POST",
    data: {'x': pos_x},
    url: "index.php",
}).done(function(msg){
   alert("data Saved: " + msg);
 });

或者将您的php更改为上面的代码,以检索原始流,如果您需要将json数据发送到服务器

答案 1 :(得分:0)

我有两个导致POST请求的重定向。在对if条件进行调整之后,这种情况不再发生,并且Ajax请求发送的数据现在也被PHP成功处理。

感谢所有花时间帮助我的人,非常感谢。