访问服务器响应(使用 XMLHttpRequest)

Accessing server responses (with XMLHttpRequest)

完成我的第一个 Web 开发 class,我决定继续参加我的小组决赛以练习 Web 开发并学习新的 Web 开发技能。

我们最终项目网站的要点是为用户提供对应于各种“主题”的复选框,并且基于这些 user-selected 主题的请求被发送到服务器。然后服务端用这些信息组成一个description,一个很大的javascript字符串,需要传回客户端渲染出来供用户阅读。

网站应如何运作的示例如下:

  1. 用户在 网站。
  2. 客户端检测到这一点并向服务器发送请求。
  3. 服务器收到此请求,查看检查了哪些主题, 然后创建一个包含的随机 description 这两个主题的内容。
  4. 服务器然后将description作为响应发送回客户端, 客户端向用户显示 description

实际上,网站能够成功完成第 1-3 步,但不能成功完成第 4 步。具体来说,虽然客户端能够从服务器接收响应,但由于某种原因它没有显示响应。

最初,我尝试使用 XMLHttpRequest.response(使用 this guide as a reference) to do step number 4, as XMLHttpRequest seemed a bit more compatible with browsers than Fetch , but I ended up simply using res.send(description) when I figured out that it was a much simpler way to get a response to the client

非常感谢任何关于如何修复以便能够在不重新加载页面的情况下显示 description 的指示。该网站使用 express、node.js 和 handlebars。如果需要更多信息,或者已经有类似问题的答案,请告诉我,我将对此进行相应的调整 post.

index.js(页面运行的脚本):

function sendGenerateRequest() {
    
    /*...Code that detects and stores what themes were selected...*/
    var descriptionBox = document.getElementByClassName('description-box')

    if(themeType == "None" || (themes === undefined || themes.length < 1)) {
        alert("You have not chosen a theme")
    } else {
        var req = new XMLHttpRequest()
        var reqUrl = "/buildgen/newGen"
        console.log("== reqUrl:", reqUrl)

        req.open('POST', reqUrl)
            var reqBody = JSON.stringify(postContent)
            req.responseType = 'text'
            req.setRequestHeader('Content-Type', 'application/json')

        req.onload = function() {
            console.log("Response: ", req.response)
            /*descriptionBox is where response should appear*/
            descriptionBox.textContent = req.response
        }

        req.send(reqBody)
    }
    //location.reload();
}

rptools.js,用node.js运行的服务器端代码,表示:

app.post("/buildgen/newGen", function(req,res,next) {

    /*...Code that creates the description string...*/

    console.log("Description: ", description)

    /*Send description as a response*/
    res.send(description)
})

选择“普通商店”和“魔法商店”时的控制台输出(服务器端):

Request received:
        url:  /buildgen/newGen
        method:  POST
        headers:  {
  host: 'localhost:3000',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0',
  accept: '*/*',
  'accept-language': 'en-US,en;q=0.5',
  'accept-encoding': 'gzip, deflate',
  'content-type': 'application/json',
  'content-length': '68',
  origin: 'http://localhost:3000',
  dnt: '1',
  connection: 'keep-alive',
  referer: 'http://localhost:3000/buildgen'
}
== req.body: {
  themeType: 'Room',
  theme: [ 'General Shop Room', 'Magic Shop Room' ]
}
Description:
    Looking to the North end of the room...
        A large book rests upon a polished oak lecturn. The book details the magical items sold at the shop.
    In the East end of the room...
        There are wooden shelves filled with smoked fish and cured meats.
    Moving to the South end of the room...
        There is a wooden table. On it are large slices of cured meats.
    Investigating the West end of the room...
        There is a weapon halfway embedded in a stone. It is (fill in the blank)
    Observing the Center of the room...
        There is a oak service desk fitted with glass, allowing items to be placed and viewed from inside the desk. On top of the desk is a small copper bell with the words "ring for service" etched into it in common.

选择“普通商店”和“魔法商店”时的控制台输出(客户端):

== reqUrl: /buildgen/newGen index.js:235:11
Response:      
    Looking to the North end of the room...
    A large book rests upon a polished oak lecturn. The book details the magical items sold at the shop.
    In the East end of the room...
    There are wooden shelves filled with smoked fish and cured meats.

    Moving to the South end of the room...
    There is a wooden table. On it are large slices of cured meats.

    Investigating the West end of the room...
    There is a weapon halfway embedded in a stone. It is (fill in the blank)

    Observing the Center of the room...
    There is a oak service desk fitted with glass, allowing items to be placed and viewed from inside the desk. On top of the desk is a small copper bell with the words "ring for service" etched into it in common.
index.js:243:12

编辑:屏幕截图显示了我正在尝试更改的 HTML 元素“textarea”:

问题有两点:

一个,在我的 sendGenerateRequest 函数中,我尝试调用 document.getElementByClassName('description-box')。此函数 存在:您只能通过 class 名称获取元素的 array,而不是 individual 元素按其 class 名称。一个简单的解决方案(以及我使用的那个)是向您希望获取的元素添加一个 id,然后使用 document.getElementById("my_id_string").

第二个问题是,正如 Barmar 在对原始 post 的评论中指出的那样,如果我有一个 <textarea> 元素,我应该将我的文本分配给 textarea.valuetextarea.textContent.