Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>
- Lines
- </title>
- </head>
- <body>
- <main>
- <form method="get"
- action="/submit">
- <input type="text" name="lines" id="lines"></input>
- <label>Perform a query to the web server</label>
- <input type="button"
- value="Using AJAX"
- onclick="requestAJAXInterval()">
- </form>
- <canvas width="200" height="200" id="canvas"></canvas>
- </main>
- </body>
- <script>
- const canvasElem = document.getElementById('canvas');
- const ctx = canvasElem.getContext('2d');
- function requestAJAXInterval() {
- let input = document.getElementById("lines");
- for(let i=0; i<input.value; ++i) {
- setTimeout(requestAJAX, 1000 * i);
- }
- }
- /*****************************************************************/
- /* 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
- let input = document.getElementById("lines");
- xhr.open('GET', '/submit?lines=' + input.value, true);
- xhr.send(null);
- // 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
- let arr = received_data.split(" ");
- draw(arr[0], arr[1], arr[2], arr[3], arr[4], arr[5], arr[6]);
- // 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 draw(startX, startY, endX, endY, r, g, b) {
- ctx.beginPath();
- ctx.strokeStyle = "rgb(" + r + ", " + g + ", " + b + ")";
- ctx.moveTo(startX, startY);
- ctx.lineTo(endX, endY);
- ctx.stroke();
- }
- </script>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement