簡體   English   中英

Ajax POST 無法從 PHP 讀取

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM