基于Open Weather Map API+Ajax的天气网站无法返回数据求助
Fixing Your Weather Temperature Lookup Website
Hey there! Let's walk through fixing your weather app code—there are a few small issues that are keeping it from working correctly.
First, Let's Break Down the Problems in Your Current Code
- Incomplete function definition: Your
successcallback starts withfuncti...which is cut off and invalid syntax. - Incorrect URL parameter separators: You used
&(HTML entity for&) in your API URL, but in JavaScript we need to use plain&to concatenate query parameters. - Unnecessary JSONP: OpenWeatherMap supports CORS, so you can use standard
jsonas yourdataTypeinstead ofjsonp(this avoids cross-domain issues without the extra complexity of JSONP). - Missing form submission prevention: If your button is inside a
<form>tag, clicking it will refresh the page by default—we need to stop that. - No error handling: Right now you don't have code to handle failed requests (like invalid city names or wrong API keys).
Here's the Corrected JavaScript Code
$(document).ready(function(){ $('#submitWeather').click(function(e){ // Prevent default form submission (if button is in a form) e.preventDefault(); var city = $("#city").val(); if (city.trim() != ''){ // Use trim() to handle empty spaces $.ajax({ url: 'https://api.openweathermap.org/data/2.5/weather?q=' + city + '&units=metric&APPID=xxx', type: "GET", dataType: "json", success: function(response){ // Example: Log the response and display temperature console.log(response); var temp = response.main.temp; $('#weatherResult').html(`<p>Temperature in ${city}: ${temp}°C</p>`); }, error: function(xhr, status, error){ // Handle errors (e.g., invalid city, API key issue) $('#weatherResult').html('<p>Oops! Could not fetch weather data. Please check the city name or your API key.</p>'); console.log('Error:', error); } }); } else { // Alert user if input is empty $('#weatherResult').html('<p>Please enter a city name!</p>'); } }); });
Example HTML to Pair With It
<!DOCTYPE html> <html> <head> <title>Weather Lookup</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <div> <input type="text" id="city" placeholder="Enter city name"> <button id="submitWeather">Get Temperature</button> <div id="weatherResult"></div> </div> <!-- Include your corrected JS here --> </body> </html>
Key Notes to Remember
- Replace
xxxin the API URL with your actual OpenWeatherMap API key (make sure it's valid and has the right permissions). - The
trim()on the city input prevents users from submitting just spaces. - The
errorcallback helps you debug issues and gives feedback to users when something goes wrong. - Using
e.preventDefault()stops the page from reloading if your button is inside a form (if it's not, you can remove this line, but it's safe to keep it anyway).
内容的提问来源于stack exchange,提问作者James Miller
相关产品推荐
相关产品推荐

