ajax与jquery和php脚本不协同工作,无法处理api数据

ykejflvf  于 2021-09-13  发布在  Java
关注(0)|答案(0)|浏览(165)

我的php脚本应该从geonames api获取数据。我遗漏了我的用户名。我想使用这个脚本为我的ajax获取数据,但是和post方法在我的ajax调用中不起作用。我没有使用post方法得到结果。我只收到405个错误。如果我将方法从post更改为get,那么它就可以工作。我可以使用正确的查询将ajax对象中的url更改为geonames url地址,并获得响应对象。我不知道如何创建我正在使用的url,该url有一个指向我的php脚本的路径,我正试图使用该路径发出请求。据我所知,php文件作为代理代表我的代码。如果我在上面的ajax中使用get url和get,那么我将返回php文件的内容。我的php在获取数据方面做错了什么?

<?php
    //comprehensive error handling.
    ini_set('display_errors', 'On');
    //report all php errors.
    error_reporting(E_ALL);

    //calculate the execution time of the script.
    $executionStartTime = microtime(true);

    //set the url variable with the required requests as the values in the url search.
    $url='http://api.geonames.org/countryInfoJSON?formatted=true&lang='.$_REQUEST['lang'].'&country='.$_REQUEST['country'].'&username=**********';

    //Initialize a cURL session
    $ch = curl_init();

    //Set the options on the given cURL session handles.
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL,$url);

    //Execute the given cURL session.
    $result=curl_exec($ch);

    //Close the cURL session.
    curl_close($ch);

    //decode the json object result.
    $decode = json_decode($result,true);    

    //The outputs
    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = intval((microtime(true) - $executionStartTime) * 1000) . " ms";
    $output['data'] = $decode['geonames'];

    //The header for our requests
    header('Content-Type: application/json; charset=UTF-8');

    //print the outputs
    echo json_encode($output); 

?>

这是我的script.js文件。它为我的html表中的不同按钮提供了jquery单击事件,我正试图使用它来触发ajax函数。我希望我的ajax文件能够从geonamesapi获取数据。

//Get country info
    $('#btnInfo').on('click', function(event) {

        //Prevent whole page reloading.
        event.preventDefault();

        //AJAX method with a settings object.
        $.ajax({
            type: "GET", //http method to send request.
            url: "library/php/getCountryInfo.php", //use php server script file as proxy for request.
            timeout: 2000,
            //dataType: "json", //type of data expected for response.
            data: {
                country: $('#selCountry').val(), //requested data.
                lang: $('#selLang').val()
            },

            //BeforeSend function
            beforeSend: function() {
                $("#txtContinent").append('<p id="LoadingContinent">Loading...</p>');
                $("#txtCapital").append('<p id="LoadingCapital">Loading...</p>');
                $("#txtLanguages").append('<p id="LoadingLanguages">Loading...</p>');  //Add loading messages to results.
                $("#txtPopulation").append('<p id="LoadingPopulation">Loading...</p>');
                $("#txtArea").append('<p id="LoadingArea">Loading...</p>');
            },

            //Complete function
            complete: function() {
                $("#LoadingContinent").remove();
                $("#LoadingCapital").remove();
                $("#LoadingLanguages").remove(); //Remove loading messages from results.
                $("#LoadingPopulation").remove();
                $("#LoadingArea").remove();
            },

            //success function
            success: function(result) {

                console.log(result);

                if (result.status == "ok") {

                    $('#txtContinent').html(result['data'][0]['continent']);
                    $('#txtCapital').html(result['data'][0]['capital']);
                    $('#txtLanguages').html(result['data'][0]['languages']);
                    $('#txtPopulation').html(result['data'][0]['population']);
                    $('#txtArea').html(result['data'][0]['areaInSqKm']);

                }

            },

            //error function
            error: function(request, errorThrown) {
                let message = "";
                if(request.status === 0) {
                    message = "You are not connected. \n Check your network connection.";
                    console.log(message);
                } else if(request.status == 404) {
                    message = "Requested content not found.";
                    console.log(message);
                } else if(request.status == 500) {
                    message = "Internal Server Error [500].";
                    console.log(message);
                } else if(errorThrown === 'parsererror') {
                    message = "Requested JSON parse failed.";
                    console.log(message);
                } else if(errorThrown === 'timeout') {
                    message = "Requested timed out.";
                    console.log(message);
                } else if(errorThrown === 'abort') {
                    message = "Ajax request aborted.";
                    console.log(message);
                }  else {
                    message = 'Uncaught Error.\n' + request.responseText;
                }
                $("#ajaxMessage").html(message); //add the message to the html page
            }
        }); 
    });

我的index.html文件。它有一个带有按钮的表格,应该在下面的段落中显示返回的数据。

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="Author" content="Patrick Trollip">
    <title>TASK:AJAX/PHP/CURL/JSON/GeonamesAPI</title>
  </head>
  <body>
    <h1>Task:</h1>
    <div id="userInputs">
      <table>
        <tr>
          <th>API Name:</th>
          <th>API Description:</th>
          <th>Inputs:</th>
        </tr>
        <tr>
          <td>countryInfo</td>
          <td>
            <label for="selCountry">Country</label>
            <select id="selCountry">
              <option value="GB">Great Britain</option>
              <option value="FR">France</option>
              <option value="DE">Germany</option>
              <option value="BR">Brazil</option>
              <option value="PT">Portugal</option>
            </select>
            <label for="selLang">Language</label>
            <select id="selLang">
              <option value="en">English</option>
              <option value="fr">French</option>
              <option value="de">Deutsche</option>
              <option value="pt">Portuguese</option>
            </select>
          </td>
          <td>
            <button id="btnInfo">Get Info</button>
          </td>
        </tr>
        <tr>
          <td>timezone</td>
          <td>
            <input type="number" id="InputTZlatitude" placeholder="Latitude">
            <input type="number" id="InputTZlongitude" placeholder="Longitude">
            <input type="number" id="InputTZradius" placeholder="Radius">
            <label for="SelTZlanguage">Language</label>
            <select id="SelTZlanguage">
              <option value="en">English</option>
              <option value="fr">French</option>
              <option value="de">Deutsche</option>
              <option value="pt">Portuguese</option>
            </select>  
          </td>
          <td>
            <button id="btnTimeZone">Get Time</button>
          </td>
        </tr>
        <tr>
          <td>weather</td>
          <td>
            <input type="number" id="coordN" placeholder="North">
            <input type="number" id="coordS" placeholder="South">
            <input type="number" id="coordE" placeholder="East">
            <input type="number" id="coordW" placeholder="West">
            <input type="number" id="maxRows" placeholder="Minimum rows 10">
            <label for="SelWeatherlanguage">Language</label>
            <select id="SelWeatherlanguage">
              <option value="en">English</option>
              <option value="fr">French</option>
              <option value="de">Deutsche</option>
              <option value="pt">Portuguese</option>
            </select>  
          </td>
          <td>
            <button id="btnWeather">Get Weather</button>
          </td>
        </tr>
        <tr>
          <td>countryCode</td>
          <td>
            <input type="number" id="InputCClatitude" placeholder="Latitude">
            <input type="number" id="InputCClongitude" placeholder="Longitude">
            <input type="number" id="InputCCradius" placeholder="Radius">
            <label for="SelCCType">CountryCode Type</label>
            <select id="SelCCType">
              <option value="GB">Great Britain</option>
              <option value="FR">France</option>
              <option value="DE">Germany</option>
              <option value="BR">Brazil</option>
              <option value="PT">Portugal</option>
            </select>  
            <label for="SelCClanguage">Language</label>
            <select id="SelCClanguage">
              <option value="en">English</option>
              <option value="fr">French</option>
              <option value="de">Deutsche</option>
              <option value="pt">Portuguese</option>
            </select>  
          </td>
          <td>
            <button id="btnCtryCode">Get Code</button>
          </td>
        </tr>
      </table>
    </div>
    <div id="userResults">
      <div>
        <h2>Country information:</h2>
        <h3>Results:</h3> <!--Display Country information results-->
        <p>Continent:<span id="txtContinent"></span></p>
        <p>Capital:<span id="txtCapital"></span></p>
        <p>Languages:<span id="txtLanguages"></span></p>
        <p>Population:<span id="txtPopulation"></span></p>
        <p>Area:<span id="txtArea"></span></p>
      </div>
      <div>
        <h2>Timezone:</h2> <!--Display Timezone results-->
        <h3>Results:</h3>
        <p>TimeZone Latitude:<span id="TZlat"></span></p>
        <p>TimeZone Longitude:<span id="TZlng"></span></p>
        <p>TimeZone Radius:<span id="TZrad"></span></p>
        <p>TimeZone Language:<span id="TZlang"></span></p>
      </div>
      <div>
        <h2>Weather:</h2> <!--Display Weather results-->
        <h3>Results:</h3>
        <p>Weather South:<span id="WeatherSouth"></span></p>
        <p>Weather West:<span id="WeatherWest"></span></p>
        <p>Weather North:<span id="WeatherNorth"></span></p>
        <p>Weather East:<span id="WeatherEast"></span></p>
        <p>Languages:<span id="WeatherLanguages"></span></p>
      </div>
      <div>
        <h2>Country Code:</h2> <!--Display Country Code results-->
        <h3>Results:</h3>
        <p>Country Code Latitude:<span id="ResultCClat"></span></p>
        <p>Country Code Longitude:<span id="ResultCClng"></span></p>
        <p>Country Code Type:<span id="ResultCCtype"></span></p>
        <p>Country Code Language:<span id="ResultCClang"></span></p>
        <p>Country Code Radius:<span id="ResultCCRad"></span></p>
      </div>
      <div id="ajaxMessage"><!--Display AJAX message here--></div>
    </div>
    <script type="application/javascript" src="library/js/jquery-3.6.0.min.js"></script>
    <script type="application/javascript" src="library/js/script.js"></script>
  </body>
</html>

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题