我在函数中有这个 Angular 代码:
function doAjax() {
$http({
method: 'POST',
url: 'http://thatsmyipv4address/MarkBeacons/www/test.php',
data: {
'dispositivo': getDevice(),
'momentoacceso': getMomentoExacto()
}
})
.then(function (data) {
alert("Data Saved: " + data.response);
console.log(data);
}, function (error) {
//alert('error: ' + error);
console.log('error: ' + error.data);
});
}
当我调用 doAjax()
时,它必须向我的 test.php 发送一条 POST 消息,其中包含 getDevice()
的值返回一个字符串,getMomentoExacto()
返回另一个字符串。
但是当我执行test.php时:
$link = mysqli_connect("localhost", "root", "", "markbeacons");
if(isset($_POST['dispositivo'])) {
$dispositivo = $_POST['dispositivo'];
} else {
$dispositivo = 'valor1';
}
if(isset($_POST['momentoacceso'])) {
$momentoacceso = $_POST['momentoacceso'];
} else {
$momentoacceso = 'valor2';
}
echo "$dispositivo";
echo "$momentoacceso";
$sql = "INSERT INTO registroEstimote (dispositivo, momentoconexion) VALUES ('$dispositivo', '$momentoacceso');";
为什么它在数据库中插入我的其他值(valor1 和 valor2)?
最佳答案
The $http.post and $http.put methods accept any JavaScript object (or a string) value as their data parameter. If data is a JavaScript object it will be, by default, converted to a JSON string.
您忘记添加此行
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
$http({
method: 'POST',
url: 'http://thatsmyipv4address/MarkBeacons/www/test.php',
data: $.param({
'dispositivo': getDevice(),
'momentoacceso': getMomentoExacto()
}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.then(function (data) {
alert("Data Saved: " + data.response);
console.log(data);
}, function (error) {
//alert('error: ' + error);
console.log('error: ' + error.data);
});
关于javascript - Angular 无法正确发送 http post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43364319/