无法在输出框中打印结果

问题描述 投票:0回答:1

请帮我解决问题,下面是我的html代码(内置css和javascript)。 问题 1. 我试图在输出框中打印结果,但页面正在刷新以创建一个正在打印结果的空白页面。 问题 2. 另外,我使用 fetch API 来发布我的请求,但我仍然必须使用表单标签,因为当我删除表单标签时,发布请求不会被触发。请帮我解决这个问题。谢谢

document.addEventListener('DOMContentLoaded', function() {
    // Helper function to validate URL format
    function isValidURL(url) {
        const urlPattern = /^(?:(?:https?|ftp):\/\/)?(?:www\.)?[\w-]+(\.[\w-]+)+[^\s]*$/i;
        return urlPattern.test(url.trim());
    }

    // Helper function to validate IP address format
    function isValidIPAddress(ip) {
        const ipPattern = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$|^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/;
        return ipPattern.test(ip.trim());
    }


   // Update the handleFormSubmission function to directly construct FormData
  function handleFormSubmission(event) {
    event.preventDefault();

    // Get selected tests
    var selectedTests = [];
    var testsCheckbox = document.querySelectorAll('input[type=checkbox][name=tests]:checked');
    testsCheckbox.forEach(function(checkbox) {
        selectedTests.push(checkbox.value);
    });

    // Get selected server
    var selectedServer = document.querySelector('select[name=server-select]').value;

    // Get test inputs
    var testInputs = document.querySelector('input[name=test-inputs]').value.split(',');

    // Validate test inputs
    var validInputs = testInputs.every(function(input) {
        return isValidURL(input) || isValidIPAddress(input);
    });

    if (!validInputs) {
        alert('Invalid input(s). Please enter valid URLs or IP addresses.');
        return;
    }

    // Construct data object
      var requestData = {
          tests: selectedTests.join(','),
          'server-select': selectedServer,
          'test-inputs': testInputs.join(',')
      };

    // Send POST request to the server using fetch API
      fetch('/run_group_tests', {
          method: 'POST',
          headers: {
              'Content-Type': 'application/json'
          },
          body: JSON.stringify(requestData)
      })
      .then(response => response.json())
      .then(data => {
          // Handle the response data
          updateOutputBox(data);
      })
      .catch(error => console.error('Error:', error));
      return false;
    }


    // Function to update the output box with the test result
  function updateOutputBox(data) {
    var outputBox = document.getElementById('output-box');
    var testResultDiv = document.createElement('div');
    testResultDiv.classList.add('test-result');

    var heading = document.createElement('h4');
    heading.textContent = data.testName;
    testResultDiv.appendChild(heading);

    data.result.forEach((line) => {
        if (line.trim()) {
          const paragraph = document.createElement('p');
          paragraph.textContent = line;
          testResultDiv.appendChild(paragraph);
        }
    });

    outputBox.appendChild(testResultDiv);
  }

  document.getElementById('test-form').addEventListener('submit', handleFormSubmission);

  // Function to download test results
  function downloadResults() {
    var results = document.getElementById('output-box').textContent;
    var blob = new Blob([results], { type: 'text/plain' });
    var url = URL.createObjectURL(blob);
    var link = document.createElement('a');
    link.href = url;
    link.download = 'test_results.txt';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    URL.revokeObjectURL(url);
    link.remove();
  }

  document.getElementById('download-results-button').addEventListener('click', downloadResults);
});
#test-form {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}

label {
  font-weight: bold;
}

input[type="text"],
select {
  width: 100%;
  padding: 8px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

input[type="checkbox"] {
  margin-right: 10px;
}

input[type="submit"] {
  background-color: #4caf50;
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

input[type="submit"]:hover {
  background-color: #45a049;
}

#output-container {
margin-top: 30px;
padding: 20px;
background-color: #FFF;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}

.test-result {
margin-bottom: 20px;
padding: 10px;
border: 1px solid #ccc;
background-color: #f9f9f9;
border-radius: 8px;
}

.test-result h4 {
margin-top: 0;
font-weight: bold;
}

.test-result p {
margin: 0;
padding: 5px 0;
}

#output-box {
border: 1px solid #ccc;
padding: 10px;
height: 150px;
overflow-y: scroll;
background-color: #FFF;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
border-radius: 8px;
}

#output-box p {
margin: 0;
padding: 5px 0;
}

#download-results {
text-align: right;
margin-top: 20px;
}

#download-results button {
background-color: #007bff;
color: #FFF;
border: none;
padding: 10px 20px;
cursor: pointer;
}

.loading-state {
display: none;
font-size: 14px;
color: #007bff;
}
<form id="test-form" method="POST" action="/run_group_tests";return false;>
  <div>
    <label for="server-select">Select ECN Server:</label><br>
    <select id="server-select" name ="server-select">
      <option value="xx,yy">xx</option>

      <option value="xx,yy">xx</option>

      <option value="xx,yy">xx</option>

      <option value="xx,yy">xx</option>

      <option value="xx,yy">xx</option>

      <option value="xx,yy">xx</option>

      <option value="xx,yy">xx</option>

      <option value="xx,yy">xx</option>

      <option value="xx,yy">xx</option>
      <!-- Add more options as needed -->
    </select>
    <br><br>

    <label>Select Tests to Run:</label><br>
    <label for="ping"><input type="checkbox" id="ping" name="tests" value="ping"> Ping</label><br>
    <label for="page-load"><input type="checkbox" id="page-load" name="tests" value="page-load"> Page Load</label><br>
    <label for="dns-lookup"><input type="checkbox" id="dns-lookup" name="tests" value="dns-lookup"> DNS Lookup</label><br>
    <label for="speed-test"><input type="checkbox" id="speed-test" name="tests" value="speed-test"> Speed Test</label><br>
    <label for="traceroute"><input type="checkbox" id="traceroute" name="tests" value="traceroute"> Traceroute</label><br>
    <label for="dhcp-lease"><input type="checkbox" id="dhcp-lease" name="tests" value="dhcp-lease"> DHCP Lease</label><br><br>

    <label for="test-inputs">Enter Test Inputs (separated by comma):</label><br>
    <input type="text" id="test-inputs" name="test-inputs"><br><br>


    <button id="submit-button" type="submit">Submit</button>
    </form>
  </div>
    
    <div id="output-container" class="rounded-corners">
    <h2>Test Results</h2>
    <div id="output-box"></div>
    </div>

    <div id="download-results">
    <button id="download-results-button">Download Results</button>
    </div>

我已经在上面粘贴了我的代码,我尝试使用 AJAX 和 fetch,但如果没有表单标签,它仍然无法工作。另外,我在使用表单标签以及 fetch api 或 ajax 时没有问题,但我怀疑由于表单标签,页面正在刷新,并且我的结果打印在新页面而不是输出框中。

javascript html ajax fetch
1个回答
0
投票

我不认为您的提交事件已停止,这就是您得到空白页面的原因。以下应该有效。我将获取请求的 URL 替换为数据 URL 只是为了测试。

document.addEventListener('DOMContentLoaded', function() {
  document.forms['test-form'].addEventListener('submit', handleFormSubmission);
  document.getElementById('download-results-button').addEventListener('click', downloadResults);
});

// Helper function to validate URL format
function isValidURL(url) {
  const urlPattern = /^(?:(?:https?|ftp):\/\/)?(?:www\.)?[\w-]+(\.[\w-]+)+[^\s]*$/i;
  return urlPattern.test(url.trim());
}

// Helper function to validate IP address format
function isValidIPAddress(ip) {
  const ipPattern = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$|^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/;
  return ipPattern.test(ip.trim());
}


// Update the handleFormSubmission function to directly construct FormData
function handleFormSubmission(event) {
  event.preventDefault();
  let form = event.target;

  // Get selected tests
  var selectedTests = [...form.tests]
    .filter(input => input.checked)
    .map(input => input.value);

  // Get selected server
  var selectedServer = form['server-select'].value;

  // Get test inputs
  var testInputs = form['test-inputs'].value.split(',');

  // Validate test inputs
  var validInputs = testInputs.every(function(input) {
    return isValidURL(input) || isValidIPAddress(input);
  });

  if (!validInputs) {
    alert('Invalid input(s). Please enter valid URLs or IP addresses.');
    return;
  }

  // Construct data object
  var requestData = {
    tests: selectedTests.join(','),
    'server-select': selectedServer,
    'test-inputs': testInputs.join(',')
  };

  // Send POST request to the server using fetch API
  fetch('data:application/json,{\"result\":[\"test\"]}', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(requestData)
    })
    .then(response => response.json())
    .then(updateOutputBox)
    .catch(error => console.error('Error:', error));
}


// Function to update the output box with the test result
function updateOutputBox(data) {
  var outputBox = document.getElementById('output-box');
  var testResultDiv = document.createElement('div');
  testResultDiv.classList.add('test-result');

  var heading = document.createElement('h4');
  heading.textContent = data.testName;
  testResultDiv.appendChild(heading);

  data.result.forEach((line) => {
    if (line.trim()) {
      const paragraph = document.createElement('p');
      paragraph.textContent = line;
      testResultDiv.appendChild(paragraph);
    }
  });
  outputBox.appendChild(testResultDiv);
}

// Function to download test results
function downloadResults() {
  var results = document.getElementById('output-box').textContent;
  var blob = new Blob([results], {
    type: 'text/plain'
  });
  var url = URL.createObjectURL(blob);
  var link = document.createElement('a');
  link.href = url;
  link.download = 'test_results.txt';
  link.target = '_blank';
  document.body.appendChild(link);
  link.click();
  URL.revokeObjectURL(url);
}
#test-form {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
}

label {
  font-weight: bold;
}

input[type="text"],
select {
  width: 100%;
  padding: 8px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

input[type="checkbox"] {
  margin-right: 10px;
}

input[type="submit"] {
  background-color: #4caf50;
  color: #fff;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

input[type="submit"]:hover {
  background-color: #45a049;
}

#output-container {
  margin-top: 30px;
  padding: 20px;
  background-color: #FFF;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.test-result {
  margin-bottom: 20px;
  padding: 10px;
  border: 1px solid #ccc;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.test-result h4 {
  margin-top: 0;
  font-weight: bold;
}

.test-result p {
  margin: 0;
  padding: 5px 0;
}

#output-box {
  border: 1px solid #ccc;
  padding: 10px;
  height: 150px;
  overflow-y: scroll;
  background-color: #FFF;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

#output-box p {
  margin: 0;
  padding: 5px 0;
}

#download-results {
  text-align: right;
  margin-top: 20px;
}

#download-results button {
  background-color: #007bff;
  color: #FFF;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}

.loading-state {
  display: none;
  font-size: 14px;
  color: #007bff;
}
<div>
  <form name="test-form" method="POST" action="/run_group_tests">
    <div>
      <label for="server-select">Select ECN Server:</label><br>
      <select id="server-select" name="server-select">
        <option value="xx,yy">xx</option>
        <option value="xx,yy">xx</option>
        <option value="xx,yy">xx</option>
        <option value="xx,yy">xx</option>
        <option value="xx,yy">xx</option>
        <option value="xx,yy">xx</option>
        <option value="xx,yy">xx</option>
        <option value="xx,yy">xx</option>
        <option value="xx,yy">xx</option>
      </select>
      <br><br>

      <label>Select Tests to Run:</label><br>
      <label for="ping"><input type="checkbox" id="ping" name="tests" value="ping"> Ping</label><br>
      <label for="page-load"><input type="checkbox" id="page-load" name="tests" value="page-load"> Page Load</label><br>
      <label for="dns-lookup"><input type="checkbox" id="dns-lookup" name="tests" value="dns-lookup"> DNS Lookup</label><br>
      <label for="speed-test"><input type="checkbox" id="speed-test" name="tests" value="speed-test"> Speed Test</label><br>
      <label for="traceroute"><input type="checkbox" id="traceroute" name="tests" value="traceroute"> Traceroute</label><br>
      <label for="dhcp-lease"><input type="checkbox" id="dhcp-lease" name="tests" value="dhcp-lease"> DHCP Lease</label><br><br>

      <label for="test-inputs">Enter Test Inputs (separated by comma):</label><br>
      <input type="text" id="test-inputs" name="test-inputs"><br><br>


      <button id="submit-button" type="submit">Submit</button>
    </div>
  </form>
</div>

<div id="output-container" class="rounded-corners">
  <h2>Test Results</h2>
  <div id="output-box"></div>
</div>

<div id="download-results">
  <button id="download-results-button">Download Results</button>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.