Проблема с аргументами при выполнении запроса AJAX POST - PullRequest
0 голосов
/ 10 ноября 2018

Я начинаю с AJAX и пробую простую программу.

У вас просто есть текстовое поле, в которое вы должны ввести имя, и когда вы нажимаете на кнопку, оно должно написать элемент «Hello -name of text field -».

Это мой AJAX-запрос с использованием GET, который работает нормально:

  function requestAJAX() {
    // Create an object representing the request to the web server - see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
    var xhr = new XMLHttpRequest(); 

    // Registration of a (user) function that will process the response received from the server
    xhr.onreadystatechange = () => response(xhr); 

    // Execution of the (asynchronous) query to the web server
    var string = '/submit';
    var add= "?name=";
    var add2= document.getElementById("myText").value;
    string=string+add+add2;
    console.log(string);
    xhr.open('GET', string, true); 
    xhr.send(null);
    // Examples of the use of the above methods - see https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
  }

и я получаю: результат

Это мой запрос с использованием POST, где указано, что отправленные данные нельзя поместить в элемент URL. Итак, я сделал это:

  function requestAJAX() {
    // Create an object representing the request to the web server - see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
    var xhr = new XMLHttpRequest(); 

    // Registration of a (user) function that will process the response received from the server
    xhr.onreadystatechange = () => response(xhr); 

    // Execution of the (asynchronous) query to the web server

    var add2= document.getElementById("myText").value;

    xhr.open('POST', '?', true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send("name="+add2);
    // Examples of the use of the above methods - see https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
  }

Я немного растерян в том, что я должен указать во втором аргументе xhr.open () при использовании POST. Я пытался с '/submit','server.js' и 'formpost.htlm', но ни один из них не работает должным образом. Любая помощь?

Это весь мой код.

form.html

    <!DOCTYPE html>
<html lang="en">
  <head>
    <h1>POST VERSION</h1>
    <meta charset="UTF-8">
    <title>
      Form
    </title>
    <script>
      /*****************************************************************/
      /* Function that performs (asynchronous) query to the web server */
      /*****************************************************************/
      function requestAJAX() {
        // Create an object representing the request to the web server - see https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
        var xhr = new XMLHttpRequest(); 

        // Registration of a (user) function that will process the response received from the server
        xhr.onreadystatechange = () => response(xhr); 

        // Execution of the (asynchronous) query to the web server

        var add2= document.getElementById("myText").value;

        xhr.open('POST', 'server.js', true);
        xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhr.send("name="+add2);
        // Examples of the use of the above methods - see https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp
      }

      /************************************************************/
      /* The function that processes the response from the server */
      /************************************************************/
      function response(xhr){
        try { 
          if (xhr.readyState == XMLHttpRequest.DONE) { // If the response is ready
            if (xhr.status == 200){                    // If requst was correct

               // If the data you receive is a plain text or a JSON document, use the following code
               var received_data = xhr.responseText;               // Get a response in the form of a string

               window.alert(received_data);          // and display it
               document.getElementById("data").innerHTML = received_data;

               // If the data you receive is an HTML or XML document, use the following code
               //var xmlDoc = xhr.responseXML; //Receive the answer in the form of object 'XmlDocument', which can be accessed using DOM methods - see https://www.w3.org/TR/domcore/
            }
            else 
               window.alert('There was a problem with this request.');
          }
        } 
        catch(e) {      
          window.alert('Exception caught: ' + e.description);
        } 
     }


      /*****************************************************************/
      /* Function that performs (asynchronous) query to the web server */
      /*****************************************************************/
      function requestFetchAPI() {
        fetch('/submit') // Execution of the (asynchronous) query to the web server - a promise is created
          .then(function(response) { // if the promise is fulfilled
            if (!response.ok) {
              throw Error(response.statusText);
            }
           window.alert(response.text()); //show the Promise object
          })
          .catch(function(error) { // if the promise is rejected
            window.alert('Looks like there was a problem: \n', error);
          });
      }
    </script>
  </head>
  <body>
    <main>
      <form method="get"
            action="/submit">
        <label>Perform a query to the web server</label> 
              <input type="text" name="name" id="myText" value="Mickey">
              <input type="submit"
              value="Without using AJAX"> 
              <input type="button"
              value="Using AJAX"
              onclick="requestAJAX()"> 
              <input type="button"
              value="Using Fetch API"
              onclick="requestFetchAPI()">
      </form>

       <p id="data"></p>


    </main>
  </body>
</html>

Server.js:

var http = require ("http");
var url = require ("url");
var fs = require ("fs");
var file = 'formpost.html';

function getUrlParameter(name, linke) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(linke);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};

http.createServer (function (request, response) {
    console.log("--------------------------------------");
    console.log("The relative URL of the current request: " + request.url + "\n");
    var url_parts = url.parse (request.url, true);  // parsing (relative) URL
    if (url_parts.pathname == '/submit') {  // Processing the form content, if the relative URL is '/ submit'
      var welcome = 'Hello';
      //var linke= decodeURI(request.url);

      var urlParams = getUrlParameter('name',request.url);
      console.log(urlParams);
      response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"}); 
      response.write(welcome + " " + urlParams);// Data (response) that we want to send to a web browser
      welcome= welcome + urlParams;
      response.end(); // Sending the answer
      console.log("The server sent the '"+welcome+"' text to the browser"); 
    }
    else { // Sending, to the browser, the contents of a file (an HTML document) with the name contained in the variable 'file'
        fs.stat(file, function (err,stats) {
          if (err == null) { // If the file exists
              fs.readFile (file, function (err, data) { // Read it content
                response.writeHead(200, {"Content-Type": "text/html; charset=utf-8"});
                response.write(data);   // Send the content to the web browser
                response.end();
              });
          }
          else { // If the file does not exists
              response.writeHead(200, {"Content-Type": "text/plain; charset=utf-8"});
              response.write('The ' + file + ' file does not exist');
              response.end();
          } //else
        }); //fs.stat
    } //else
}).listen(8080);
console.log("The server was started on port 8080");
console.log("To end the server, press 'CTRL + C'");
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...