javascript php文件中未定义的数组键,Jquery中 AJAX 调用的POST请求

63lcw9qa  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(103)

我正在做一个小项目,当用户单击按钮时,我必须获取一些天气信息。
由于某些原因,我的$_REQUEST数组不包含所需的键,即使我似乎已经在HTML表单和JS中输入了正确的设置。
如果这个错误看起来很愚蠢,我很抱歉,但我是PHP的新手,因此为什么会出现这种混乱。
// PHP //

<?php

//var_dump($_REQUEST);
ini_set('display_errors', 'On');
error_reporting(E_ALL);

$executionStartTime = microtime(true);

$url =
    'https://api.openweathermap.org/data/2.5/weather?lat=' .
    $_REQUEST['latitude'] .
    '&lon=' .
    $_REQUEST['longitude'] .
    '&appid=mykey';

$ch = curl_init();

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);

$data = curl_exec($ch);

curl_close($ch);
//$encode = json_encode($data);
$decode = json_decode($data, true);
//echo($_REQUEST);
header('Content-Type: application/json; charset=UTF-8');

?>

/// JS/JQUERY

        $.ajax({
            url: "../project1/php/weather.php",
            type: 'POST',
            dataType: 'json',
            data: {
                latitude: $('#latitude').val(),
                longitude: $('#longitude').val()
            },
            success: function (result) {

                console.log(JSON.stringify(result));

                if (result) {

                    // to be updated

                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(JSON.stringify(errorThrown));
            }
        });

    }).addTo(map);


/// HTML//

.....

<body>
    <form method="POST">
        <input type="number" name="latitude" id="latitude" step="0.01"/>
        <input type="number" name="longitude" id="longitude" step="0.01"/>
        <input type="submit" value="submit">
    </form>
    <nav class="navbar">
        <img src="globeBig.png" class="logo"/>
        <h1>The Gazetteer</h1>
        <ul class="list">
            <li>Country Information</li>
            <li>Weather</li>
            <li>Earthquakes</li>
            <li>
                <select class="country"></select>
            </li>
        </ul>
    </nav>
    <div id="map"></div>

....

ifsvaxew

ifsvaxew1#

使用 AJAX 请求加载附加信息必须从客户端到服务器端完成,其中服务器端处理的最终结果将用于更新客户端上的初始页面。
所以你需要两个文件......比如index.phpweather.php
首先在浏览器中加载index.php...与页面交互,以便向weather.php发送 AJAX 请求。
然后,响应必须由index.php的初始负载处理。
你所犯的错误是页面在发送 AJAX 请求的同时重新加载(如果发送了......在这种情况下,响应将以虚无结束)。
试试看!

索引:

<html>
  <head>
    <!-- stuff here-->
    <!-- like jQuery lib -->
  </head>
  <body>
      <form method="POST">
          <input type="number" name="latitude" id="latitude" step="0.01"/>
          <input type="number" name="longitude" id="longitude" step="0.01"/>
          <input type="submit" value="submit">
      </form>
      <nav class="navbar">
          <img src="globeBig.png" class="logo"/>
          <h1>The Gazetteer</h1>
          <ul class="list">
              <li>Country Information</li>
              <li>Weather</li>
              <li>Earthquakes</li>
              <li>
                  <select class="country"></select>
              </li>
          </ul>
      </nav>
      <div id="map"></div>
      
      <script>
        
      document.addEventListener('DOMContentLoaded', () => {
      
          $('form').on('submit', function(event){ 
              
              // Will NOT submit the page to allow re ajaxe resquest below
              event.preventDefault()
              
              $.ajax({
                  url: "../project1/php/weather.php",
                  type: 'POST',
                  dataType: 'json',
                  data: {
                      latitude: $('#latitude').val(),
                      longitude: $('#longitude').val()
                  },
                  success: function (result) {

                      // No need to stringify the result, it already is a JSON string
                      console.log(result);
                      
                      // But you need to parse it
                      const response = JSON.parse(result)

                      if (response && response.success) {

                          // Here, instanciate the leaflet.js map using response.data

                      }
                  },
                  error: function (jqXHR, textStatus, errorThrown) {
                      console.log(JSON.stringify(errorThrown));
                  }
              })
          })
      })
      </script>
  </body>
</html>

weather.php:

<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);

header('Content-Type: application/json; charset=UTF-8');
$encode = json_encode('{success: false, data: null}');

// If there are coordinates
if(isset($_REQUEST['latitude']) && isset($_REQUEST['longitude'])){
    $url =
        'https://api.openweathermap.org/data/2.5/weather?lat=' .
        $_REQUEST['latitude'] .
        '&lon=' .
        $_REQUEST['longitude'] .
        '&appid=mykey';

    $ch = curl_init();

    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);

    $data = curl_exec($ch);

    curl_close($ch);
    
    $encode = json_encode('{success: true, data: ' . $data . '}');
}

// The sent out JSON
echo $encode;
?>

相关问题