使用 jQuery $.post
函数,如果您发送一个 null
值,它作为 "null"
到达服务器端。示例:
Javascript:
$.post('test.php', { foo : null });
PHP:
var_dump($_POST['foo']); // string(4) "null"
我明白为什么会这样,但想知道解决该限制的最佳方法吗?你应该:
- 在发送之前循环遍历 JS 中的所有变量并替换为空字符串?
- 在服务器端将
“null”
解释为null
? - 根本不发送变量?
- 还有别的吗?
最佳答案
我会把它编码成 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/