[英]Ajax POST can't read from PHP
我正在写一个 javascript 并想通过 ajax POST 将数据发送到 PHP 页addProject-logic.php
。
虽然在 javascript 上 POST 请求成功,但在我的 php 页面上我无法回显,它显示undefined "latLng"
我的文件结构:结构
添加地图.js:
google.maps.event.addListener(marker, 'dragend', function (marker) {
var latLng = marker.latLng
currentLatitude = latLng.lat()
currentLongitude = latLng.lng()
var latlng = {
lat: currentLatitude,
lng: currentLongitude,
}
//Post LAT LNG TO POST
function postLatLng() {
$.ajax({
type: 'POST',
url: '../includes/actions/addProject-logic.php',
data: {
latLng: latlng,
},
success: function (response) {
window.alert('Success')
},
})
}
var geocoder = new google.maps.Geocoder()
geocoder.geocode(
{
location: latlng,
},
function (results, status) {
if (status === 'OK') {
if (results[0]) {
input.value = results[0].formatted_address
map.setZoom(18)
map.panTo(latLng)
postLatLng()
} else {
window.alert('No results found')
}
} else {
window.alert('Geocoder failed due to: ' + status)
}
},
)
})
我创建一个 function postLatLng
然后在另一个动作中执行
每当我回显 php addProject-logic.php
页面时, echo $_POST['latLng'];
它显示未定义的数组键latLng
您的示例有点含糊,因为您没有显示addProject-logic.php
文件的作用,但这是一个带有 javascript 调用和 php 代码的新示例。
我通过使用 javascript(你可以转换为 jQuery)和删除地理编码来简化,因为它似乎不是这里的问题(但是,你的例子是模糊的)。
我正在使用fetch
发出请求以显示不同的步骤。 注意JSON.stringify
调用。
// Data is
var latlng = {
lat: 42,
lng: 42
}
function postLatLng() {
fetch('addProject-logic.php', {
method: 'POST',
body: JSON.stringify({
latLng: latlng
})
})
// the response sent back via php is json
.then(response => response.json())
.then(json => {
// The data returned by the php script contains latLng
window.alert(json.latLng)
})
.catch(err => {
console.error(err)
})
}
在php这边:
<?php
// Header for the JSON response
header('Content-Type: application/json; charset=UTF-8');
// parsing the post content
// My guess is you miss both this call and the JSON.stringify in the js
$data = json_decode(file_get_contents('php://input'), true);
// here we send back the post data.
echo json_encode([
'latLng' => $data["latLng"],
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.