如何在jQuery的get方法中将文本框输入拼接至API URL端点并绑定回调
Fixing Your Wikipedia API Search with jQuery
Let's break down the issues in your current code and fix it so it properly gets input from a textbox, builds the API URL, and fetches results when the user initiates a search.
What's Wrong with the Original Code?
- You're making the API call immediately when the page loads, but at that point
searchStringis a function (not actual user input), so your URL will append the function itself instead of a valid search term. - There's no trigger for when the user actually enters a search term (like clicking a button or pressing enter).
- The
searchStringfunction isn't being used to retrieve the input value correctly.
Corrected Implementation
First, add the necessary HTML for the textbox and search button:
<input type="text" id="searchInput" placeholder="Enter search term..."> <button id="searchBtn">Search Wikipedia</button>
Now here's the fixed jQuery code:
$(document).ready(function() { // Attach click event to the search button $("#searchBtn").click(function() { // Get the current value from the textbox (trim extra spaces) const searchString = $("#searchInput").val().trim(); // Don't make the API call if input is empty if (!searchString) { alert("Please enter a search term!"); return; } // Build the API URL with the user's search term const apiUrl = `https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=${searchString}&namespace=0&limit=10&origin=*`; // Send the GET request and handle the response $.get(apiUrl, function(response) { console.log("Search Results:", response); // Process results here (e.g., display article titles: console.log(response[1])) }) .fail(function(error) { // Handle request errors console.error("Error fetching data:", error); }); }); // Optional: Allow pressing Enter to trigger search $("#searchInput").keypress(function(e) { if (e.which === 13) { // Enter key code $("#searchBtn").click(); } }); });
Key Improvements:
- User-triggered search: The API call only runs when the user clicks the button or presses Enter, ensuring we have a valid search term.
- Proper input retrieval: We grab the textbox value at the time of the search, so it's always up-to-date.
- Empty input check: Prevents unnecessary API calls with empty strings.
- Error handling: Added a
.fail()callback to catch and log request errors. - Clean URL construction: Uses template literals (`) to make the URL easier to read and maintain.
How It Works:
- When the page loads, we set up event listeners for the search button and textbox.
- When the user initiates a search, we get the input value, trim extra spaces, and validate it's not empty.
- We build the full API URL using the search term.
- We send the GET request to Wikipedia's API, and when the response comes back, we log it (or process it further to display results on the page).
内容的提问来源于stack exchange,提问作者Sai Yerni Akhil
相关产品推荐
相关产品推荐

