在JS中,可以使用XMLHttpRequest对象来发起POST网络请求。以下是一个示例代码:

// 创建XMLHttpRequest对象
var xhr = new XMLHttpRequest();

// 设置请求方法和URL
xhr.open('POST', 'http://example.com/api');

// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/json');

// 设置请求体
var data = { name: 'John Doe', age: 30 };
xhr.send(JSON.stringify(data));

// 监听请求状态变化
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 200) {
      // 请求成功
      console.log(xhr.responseText);
    } else {
      // 请求失败
      console.log('Error: ' + xhr.status);
    }
  }
};

在上面的示例代码中,我们创建了一个XMLHttpRequest对象,并设置了请求方法为POST、URL为http://example.com/api,请求头为application/json,请求体为{name: 'John Doe', age: 30}。然后我们监听了XMLHttpRequest对象的onreadystatechange事件,当请求状态变化时,我们判断请求状态和状态码,如果请求成功,就输出响应内容,否则输出错误信息。

js发起POST网络请求

原文地址: http://www.cveoy.top/t/topic/bqvr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录