问题描述
我必须使用 PHP 从 geonames API 获取数据,并使用 JQuery ajax 方法从 PHP 文件中获取数据以加载到我的 html 文件中。现在我很困惑为什么我的 PHP 文件什么都不做。我曾尝试使用 XAMPP 服务器读取 PHP 脚本数据,但我得到的只是 PHP 文件的文件内容。有人知道我可以搜索任何有用的关键字来找到同时使用 PHP、JQuery AJAX 和 API 的答案吗?
<?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 文件获取 PHP 文件以从 geonames api 获取数据。
//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>
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)