使用javascript

时间:2019-03-21 05:28:52

标签: node.js ajax post get xmlhttprequest

如何使用javascript将客户端的表单输入传递给服务器?下面是客户端。我想使用用户名或在文本框中输入的任何内容,然后将其发送到server.js,在此将对其进行处理以进行验证。事实是,我需要将client.js中的数据存储在server.js中的变量中,以便能够检索它。

 var textbox;
 var dataDiv;
 window.onload = init;

function init(){
    textbox = document.createElement("input");
    textbox.id="textbox";
    dataDiv = document.createElement("div");
    var header = document.createElement("h1");
    header.appendChild(document.createTextNode("Select User"));
    var button = document.createElement("BUTTON");
    button.id = "myBtn";
    var textBtn = document.createTextNode("Click me");
    button.appendChild(textBtn);
    button.addEventListener("click", () => {
    sendData();
});

var docBody = document.getElementsByTagName("body")[0];//Only one body

    docBody.appendChild(header);
    docBody.appendChild(dataDiv);
    docBody.appendChild(textbox);
    docBody.appendChild(button);
}

function sendData(){
     var usrName = document.getElementById("textbox").value; //I want to send it to server.js
     var xhttp = new XMLHttpRequest();
     xhttp.onreadystatechange = function() {
     if (this.readyState == 4 && this.status == 200) {
           var dataObj = JSON.stringify(this.responseText);
           dataDiv.innerHTML = dataObj;
     }
 };
 xhttp.open("GET", "/register", true);
 xhttp.send();
}

这是服务器端

 var express = require('express');
 var app = express();
 app.get('/register', handleGetRequest); //how do I pass usrName here?
 app.use(express.static('public'));
 app.listen(5000);

 function handleGetRequest(request, response){
      var pathArray = request.url.split("/");
      var pathEnd = pathArray[pathArray.length - 1];
      if(pathEnd === 'register'){
          response.send("{working}");
      }
      else
         response.send("{error: 'Path not recognized'}");
}

2 个答案:

答案 0 :(得分:0)

如果使用GET,则必须将参数放在URL中。

xhttp.open("GET", "/register?usrName=" + encodeURIComponent(usrName), true);

有关如何在Express中读取查询参数的信息,请参见How to get a URL parameter in Express?

答案 1 :(得分:0)

发送数据:

function sendData(){
  var usrName = document.getElementById("textbox").value; //I want to send it to server.js
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          var dataObj = JSON.stringify(this.responseText);
          dataDiv.innerHTML = dataObj;
      }
  };
  xhttp.open("GET", "http://localhost:5000/register?usrName=" + encodeURIComponent(usrName), true);
  xhttp.send();
}

读取数据:

function handleGetRequest(request, response){
  var urlParts = request.url.split("?");
  if(urlParts[0] === '/register'){
      var usrName = urlParts[1].replace('usrName=', '');
      response.send("{" + usrName + "}");
  }
  else
    response.send("{error: 'Path not recognized'}");
}