我遇到了JSON,即客户端代码:
$.getJSON('http://freegeoip.net/json/?callback=?', function(userData) {
console.log(JSON.stringify(userData, null, 2));
});
$.ajax({
type: "POST",
url: "listener.php",
data: JSON.stringify($.userData),
success: function(res) {
alert(res);
}
})
和php服务器端代码:
$data = json_decode($_POST['userData']);
$response = 'I got parameters '.count($data).'\n';
foreach ($data as $key=>$value) {
$response .= 'key: '.$key.'; value: '.$value.'\n';
}
echo $response;
关键是我没有错误,但看起来像php没有得到任何数据或无法序列化它,我刚开始学习网络编程,我会很高兴任何建议,谢谢!
答案 0 :(得分:0)
JavaScript的:
$.ajax({
type: "POST",
url: "listener.php",
data: {'foo':'bar'},
success: function(res) {
alert(res);
}
});
PHP:
$data = $_POST;
$response = 'I got parameters '.count($data).'\n';
foreach ($data as $key=>$value) {
$response .= 'key: '.$key.'; value: '.$value.'\n';
}
echo $response;
答案 1 :(得分:0)
使用Javascript:
$.getJSON('http://freegeoip.net/json/', function(userData) {
console.log(JSON.stringify(userData, null, 2));
$.ajax({
type: "POST",
url: "listener.php",
data: userData,
success: function(res) {
alert(res);
}
})
});
PHP:
$data = $_POST;
$response = 'I got parameters '.count($data).'\n';
foreach ($data as $key=>$value) {
$response .= 'key: '.$key.'; value: '.$value.'\n';
}
echo $response;
注意:为了进一步使用(例如在数据库查询中),您应该转义收到的数据以避免注入!