Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

AJAX原理之POST #140

Open
JasonWu73 opened this issue Jul 15, 2020 · 0 comments
Open

AJAX原理之POST #140

JasonWu73 opened this issue Jul 15, 2020 · 0 comments
Labels
参考 示例程序
Projects

Comments

@JasonWu73
Copy link
Owner

<!DOCTYPE html>
<html lang="zh">
<head>
  <meta charset="UTF-8">
  <title>AJAX请求</title>
</head>
<body>

<textarea id="txt" cols="60" rows="6"></textarea>

<script>
  const url = "http://localhost:8080/test";
  const params = 'id=101&title=怎一个爽字了得';

  /**
   * 发送同步请求
   */
  const sendSyncRequest = (url, params) => {

    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, false); // 同步

    // 设置正确的请求头
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    xhr.send(params); // 发送请求

    // 读取响应数据并展示
    document.querySelector('#txt').innerHTML = xhr.responseText;

    console.log('完成');
  };

  /**
   * 发送异步请求
   */
  const sendAsyncRequest = (url, params) => {

    const xhr = new XMLHttpRequest();
    xhr.open('POST', url); // 异步

    // 设置正确的请求头
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    // 读取响应数据并展示
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        // 请求成功
        document.querySelector('#txt').innerHTML = xhr.responseText;
      }
    }

    xhr.send(params); // 发送请求

    console.log('完成');
  };

  /**
   * 通过ES6 Promise封装AJAX
   */
  const ajax = (url, params) => new Promise((resolve, reject) => {

    const xhr = new XMLHttpRequest();
    xhr.open('POST', url); // 异步

    // 设置正确的请求头
    xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

    // 读取响应数据并展示
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4 && xhr.status === 200) {
        // 请求成功
        resolve({data: xhr.responseText});
      } else if (xhr.readyState === 4) {
        // 请求失败
        reject(xhr.responseText);
      }
    }

    xhr.send(params); // 发送请求

    console.log('完成');
  });

  sendSyncRequest(url, params);

  // sendAsyncRequest(url, params);

  // ajax(url, params).then(({data}) => {
  //   document.querySelector('#txt').innerHTML = data;
  // }).catch(err => {
  //   console.log(err);
  // });

</script>
</body>
</html>
@JasonWu73 JasonWu73 added the 参考 示例程序 label Jul 15, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
参考 示例程序
Projects
JavaScript
Awaiting triage
Development

No branches or pull requests

1 participant