javascript - 通过 AJAX 发布空值

标签 javascript jquery ajax post

使用 jQuery $.post 函数,如果您发送一个 null 值,它作为 "null" 到达服务器端。示例:

Javascript:

$.post('test.php', { foo : null });

PHP:

var_dump($_POST['foo']); // string(4) "null"

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

  1. 在发送之前循环遍历 JS 中的所有变量并替换为空字符串?
  2. 在服务器端将 “null” 解释为 null
  3. 根本不发送变量?
  4. 还有别的吗?

最佳答案

我会把它编码成 JSON。

例如:

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

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

$msg = json_decode(file_get_contents("php://input"));
var_export($msg->foo); // NULL

关于javascript - 通过 AJAX 发布空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3042524/

相关文章:

javascript - javascript字符串+变量中的引号

javascript - VSCode Linter ES6 ES7 Babel linter

javascript - 如何仅在设备处于 xs View 时添加点击处理程序?

jQuery 验证 : Display group error message until all fields are correct

asp.net - 页面加载时的 Ajax 操作链接

javascript - CKEditor - 图像属性对话框为空

javascript - 为什么更改参数的副本会更改参数?

javascript - Jquery插件构造ID

jQuery GET 不读取 IE 中的 HTML 响应数据

php - 在同一个表中保存多个 JQuery Sortable