【问题标题】:Make HTTP request to web API using regular JavaScript使用常规 JavaScript 向 Web API 发出 HTTP 请求
【发布时间】:2019-03-05 00:50:40
【问题描述】:

我正在尝试访问返回 JSON 对象的服务器上的 php 脚本。我正在尝试使用纯 JS(不是 jQuery 或 React)来做到这一点。

我有以下JS:

//Define Parameters:
var param1 = document.getElementById("param1");
var param2 = document.getElementById("param2");

//Send data to the server:
function sendData() {

    var XHR = new XMLHttpRequest();

    //On Success:
    XHR.addEventListener("load", function(event) {
        alert(event.target.responseText);
    });

    //On Fail:
    XHR.addEventListener("error", function(event) {
        alert('Oops! Something went wrong.');
    });

    //Setup the request:
    XHR.open("POST", "https://www.example.com/folder/file.php");
    XHR.setRequestHeader('Content-Type', 'application/json');

    //Perform the request:
    XHR.send(JSON.stringify({
        param1: param1,
        param2: param2
    }));

}

这些参数由用户从 HTML 页面输入。似乎请求没有发送到 POST 参数,request typeOPTIONS 而不是 POST

编辑 1:

按照 cmets 中的建议,我尝试了一个获取请求并且该请求正在运行。它似乎没有通过我的 POST 参数。我的代码如下。

//Define Parameters:
var param1 = document.getElementById("param1");
var param2 = document.getElementById("param2");

var formData = new FormData(document.getElementById('form'));
formData.append('param1', param1);
formData.append('param2', param2);

//Send data to the server:
function sendData() {

    var url = 'https://www.example.com/folder/file.php';

    fetch(url, {
    method: 'POST',
    body: formData,
    headers:{
        'Accept': 'application/json',
        'Content-Type': 'multipart/form-data'
    }
    }).then(res => res.json())
    .then(response => console.log('Success:', JSON.stringify(response)))
    .catch(error => console.error('Error:', error));

}

【问题讨论】:

  • 你考虑过使用fetch更多信息在这里developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
  • @SGhaleb 我已更改为获取请求,但它似乎没有将我的参数传递给我的脚本,因为我现在正在接收用户输入错误凭据时应该接收的内容。我将编辑我的答案以反映我的新代码。

标签: javascript post https


【解决方案1】:

删除fetch 请求中的headers 部分,以便使用默认值。

【讨论】:

  • 我试图删除标题,同样的问题。参数未发送。
【解决方案2】:

您是否检查过获取请求中发送的数据类型是否正确?字段中接收到的错误类型可能会影响您看到的结果。你收到什么错误? 此链接还可能描述您在获取时遇到的问题: https://stanko.github.io/uploading-files-using-fetch-multipart-form-data/

(这确实应该是一个评论,但我没有这方面的声誉,抱歉)。

【讨论】:

  • 没有错误代码。请求已成功完成,但参数未传递给 PHP。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-11
  • 2018-11-26
  • 1970-01-01
  • 2017-06-06
  • 2018-09-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多