JavaScript对象未正确发布到后端

时间:2018-03-16 09:30:00

标签: javascript php jquery ajax

尝试使用jQuery 2.1.x到PHP 7.1代码发布 JS对象时,PHP后端会收到一个空对象,其中包含以下代码:

JS:

$("#newTabLink").click(function(e) {
      ntn++;
      console.log('ntn = ' + ntn + ' / id =' + id);
      id++;
      var tabData = new Object();
      var tc = $('#tabs').children().length;
      console.log('tc = ' + tc)
      tabData.label = 'New Tab ' + ntn;
      tabData.pos = tc;
      $.ajax({
        url: 'services/save_obj.php',
        type: 'POST',
        data: JSON.stringify(tabData),
        async: true,
        dataType: 'json',
        cache: false,
        contentType: "application/json; charset=utf-8",
        encode: true,

        success: function(response) {
          if (response.success == true) {
            id = response.id;
          } else if (response.success == false) {
            alert('Aww, something went wrong!');
          }
        }
        });
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

services / save_obj.php:

if (isset($_POST)) {
    $strvalue = filter_input(INPUT_POST, 'label', FILTER_SANITIZE_STRING);
    $user_id = filter_input(INPUT_POST, 'objsay', FILTER_VALIDATE_INT);
    $lang = filter_input(INPUT_POST, 'lng', FILTER_SANITIZE_STRING);
    $location = filter_input(INPUT_POST, 'loc', FILTER_SANITIZE_STRING);
    $position = filter_input(INPUT_POST, 'pos', FILTER_SANITIZE_STRING);

    var_dump($_POST);
}

抓住我的脑袋弄清楚我在这里做错了什么。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果从前端应用程序发送JSON数据,您可以使用php:// input将数据发现到php脚本中。

示例:

服务/ save_obj.php

$input = file_get_contents('php://input');
if(!empty($input)){
   $input = json_decode($input, true);
   // ... some logic
}

您可以使用全局$ _POST,仅使用表单数据。

相关问题