通过AJAX发布空值

nic*_*ckf 14 javascript ajax jquery post

使用jQuery $.post函数,如果发送一个null值,它就会到达服务器端"null".例:

使用Javascript:

$.post('test.php', { foo : null });
Run Code Online (Sandbox Code Playgroud)

PHP:

var_dump($_POST['foo']); // string(4) "null"
Run Code Online (Sandbox Code Playgroud)

我理解为什么会这样,但是想知道解决限制的最佳方法?你应该:

  1. 在发送它们之前遍历JS中的所有变量并用空字符串替换?
  2. 解释"null"null服务器端?
  3. 根本不发送变量?
  4. 别的什么?

Mat*_*hen 14

我会把它编码成JSON.

例如:

$.ajax({
  url: 'test.php',
  type: 'POST',
  data: JSON.stringify({foo : null}),
  contentType: "application/json",
  success: function(data) {
    // ...
  }
});
Run Code Online (Sandbox Code Playgroud)

您可以json_decode在服务器上使用,并保留类型:

$msg = json_decode(file_get_contents("php://input"));
var_export($msg->foo); // NULL
Run Code Online (Sandbox Code Playgroud)