发送数据和接收依赖于该数据的响应的最佳方法是什么?
考虑用于请求的PHP文件:
$test = $_POST['test'];
echo json_encode($test);
我尝试用以下方法做得不够:
$.ajax({
type: "POST",
dataType: "json",
data: '{test : worked}',
url: 'ajax/getDude.php',
success: function(response) {
alert(response);
}
});
答案 0 :(得分:8)
丢失引号以传递对象:
$.ajax({
type: "POST",
dataType: "json",
data: {test : worked},
url: 'ajax/getDude.php',
success: function(data) {
alert(data);
}
});
答案 1 :(得分:5)
而不是这个
data: '{test : worked}'
尝试
data: {"test" : worked} // Worked being your data you want to pass..
data: {"test" : "worked"} // Else enclose worked in quotes
答案 2 :(得分:1)
问题似乎是您提交的是字符串而不是json对象 - 将data: '{test : worked}'
更改为data: {test : 'worked'}