You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DOM选择器作业疑问及从app.js获取图书数据的技术求助

Hey there! Let's break down your problems step by step and fix them up.

1. Using document.getElementById to Get Search Input Value

You mentioned wanting to use native JS's document.getElementById to fetch the search box value—this is straightforward, and works just like the jQuery approach you already have:

// Native JS way to get the book title from the search box
var title = document.getElementById('title').value;

Feel free to stick with this or keep using jQuery's $("#title").val()—both will get you the input value, so pick whichever you're more comfortable with.

2. Fixing the Book Data Fetch Logic

Looking at your app.js core data, it's an array of book objects:

[{"author":"me","title":"BookA","pages":600,"quality":"new"},{"author":"you","title":"BookB","pages":400,"quality":"used"},{"author":"us","title":"BookC","pages":500,"quality":"old"}]

But your front-end AJAX code tries to access info.book.title—this is the root of your problem! The backend returns an array, not an object with a book property. Let's fix that, plus add some robustness to the request.

Revised Front-End Code (Fixed AJAX Logic)

I've adjusted your code to use native JS for input retrieval, fix the data handling, and add error checking:

<head>
<title>Books - ExpressJS Web Application</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    $("#submit").click(function() {
        // Use native JS to get the search input value
        var title = document.getElementById('title').value.trim();
        
        // Basic validation to avoid empty requests
        if (!title) {
            alert("Please enter a book title!");
            return;
        }

        var url = "http://localhost:3000/book?title=" + encodeURIComponent(title);
        var xhttp = new XMLHttpRequest();
        
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4) {
                if (this.status == 200) {
                    var books = JSON.parse(this.responseText);
                    // Find the matching book from the returned array
                    var matchedBook = books.find(book => book.title.toLowerCase() === title.toLowerCase());
                    
                    if (matchedBook) {
                        // Populate the output fields with native JS
                        document.getElementById('data-title').value = matchedBook.title;
                        document.getElementById('data-author').value = matchedBook.author;
                        document.getElementById('data-pages').value = matchedBook.pages;
                        document.getElementById('data-condition').value = matchedBook.quality;
                    } else {
                        alert("No book found with that title!");
                        // Clear fields if no match
                        document.getElementById('data-title').value = "";
                        document.getElementById('data-author').value = "";
                        document.getElementById('data-pages').value = "";
                        document.getElementById('data-condition').value = "";
                    }
                } else {
                    alert("Request failed with status code: " + this.status);
                }
            }
        };
        
        xhttp.open("GET", url, true);
        xhttp.send();
    });
});
</script>
<style>
input { width: 100px }
label { display: inline-block; text-align: right; }
#output { width: 200px }
.data { margin-bottom: 5px; }
.finput { float: right; }
</style>
</head>
<body>
<div class="search">
Search Book Title:<br><br>
<input id="title" type="text" name="book_title" />
<button id="submit" type="button">Search</button><br><br>
</div>
<div id="output">
Data:<br><br>
<label class="data" for="data-title">Title</label>
<input id="data-title" class="finput" type="text" name="book_info" readonly/>
<br>
<label class="data" for="data-author">Author</label>
<input id="data-author" class="finput" type="text" name="book_info" readonly/>
<br>
<label class="data" for="data-pages"># Pages</label>
<input id="data-pages" class="finput" type="text" name="book_info" readonly/>
<br>
<label class="data" for="data-condition">Condition</label>
<input id="data-condition" class="finput" type="text" name="book_info" readonly/>
</div>
</body>
</html>

Key Changes Explained:

  • Used document.getElementById to fetch the search input value as requested
  • Added input validation to prevent empty search requests
  • Used encodeURIComponent() to handle special characters in book titles
  • Fixed data parsing: since the backend returns an array, we use Array.find() to locate the matching book
  • Added error handling for failed requests and missing book matches
  • Set output fields to readonly to prevent accidental edits

Backend (app.js) Adjustment (If Needed)

If your backend hasn't been set up to filter books by title, add this logic (for Express.js):

const express = require('express');
const app = express();

// Your book dataset
const books = [
    {"author":"me","title":"BookA","pages":600,"quality":"new"},
    {"author":"you","title":"BookB","pages":400,"quality":"used"},
    {"author":"us","title":"BookC","pages":500,"quality":"old"}
];

// Handle book search requests
app.get('/book', (req, res) => {
    const title = req.query.title;
    if (!title) {
        // Return all books if no title is provided
        res.json(books);
    } else {
        // Filter books by title (case-insensitive)
        const matchedBooks = books.filter(book => book.title.toLowerCase() === title.toLowerCase());
        res.json(matchedBooks);
    }
});

app.listen(3000, () => console.log('Server running on port 3000'));

With these changes, you'll be able to search for and retrieve data for BookA, BookB, or BookC smoothly!

内容的提问来源于stack exchange,提问作者Duz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:00:12