执行AJAX POST请求时参数出现问题

时间:2018-11-10 15:55:14

标签: html node.js ajax request

我从AJAX开始,正在尝试一个简单的程序。

您只有一个文本字段,您必须在其中输入名称,单击按钮时,它应该写在元素“ Hello-文本字段名称-”上。

这是我使用GET的AJAX请求,效果很好:

  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
  }

然后我得到:result

这是我使用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
  }

使用POST时,我在xhr.open()的第二个参数中输入的内容有些困惑。我尝试使用'/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'");

0 个答案:

没有答案