我试图一次掌握比我应该掌握的更多内容。
假设我有 2 个输入和一个按钮,单击按钮时我想创建一个包含这些输入数据的 json 并将其发送到服务器。
我认为这应该可以做到,但我可能是错的,因为我见过很多不同的(解释不清的)方法来做类似的事情。
var Item = function(First, Second) {
return {
FirstPart : First.val(),
SecondPart : Second.val(),
};
};
$(document).ready(function(){
$("#send_item").click(function() {
var form = $("#add_item");
if (form) {
item = Item($("#first"), $("#second"));
$.ajax ({
type: "POST",
url: "post.php",
data: { 'test' : item },
success: function(result) {
console.log(result);
}
});
}
});
});
在 PHP 中我有
class ClientData
{
public $First;
public $Second;
public function __construct($F, $S)
{
$this->First = F;
$this->Second = S;
}
}
if (isset($_POST['test']))
{
// do stuff, get an object of type ClientData
}
问题是 $_POST['test'] 似乎是一个数组(如果我将它传递给 json_decode 我会得到一个错误,指出它是一个数组,如果我使用 foreach 迭代它,我会得到我期望的值查看)。 这个ajax调用正确吗?我还应该在 PHP 方面做些什么吗?
最佳答案
您应该指定 json 内容类型并使用 JSON.stringify()格式化数据负载。
$.ajax ({
type: "POST",
url: "post.php",
data: JSON.stringify({ test: item }),
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result);
}
});
关于javascript - ajax - 将数据作为 json 发送到 php 服务器并接收响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34620527/