使用提取API

时间:2018-11-22 02:39:09

标签: php ajax post fetch

我正在使用fetch将POST请求发送到后端“ ajax-admin.php”,然后重定向到我在functions.php中具有的php函数。 我决定用'fetch'API替换xmlHttpRequests。 我用这样的提取方式进行发布请求:

fetch(url, {
        method: 'POST',

        credentials: "include",
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }


      })
    .then(res => res.json())
    .then(data => resolve(data)) // we call resolve with the data
    .catch(err => reject(err));

  });

URL的查询字符串的格式为:action=login&tokend_id=1234

在服务器端,我使用$ _POST检索参数“ action”和“ token_id”的值。 但是我看到的是$ _POST为空,而$ _REQUEST确实有参数。因此,如果我执行$ _POST ['token_id'],则会收到错误消息,因为$ _POST为空。但是,如果我执行$ _REQUEST ['token_id'],则会得到该参数的值。

知道为什么会这样吗? 为什么参数在$ _REQUEST中而不在$ _POST中。

我用以下语句检查$ _POST是否为空:

 if ( isset( $_POST ) && 0 === count($_POST) ) 

谢谢

1 个答案:

答案 0 :(得分:2)

  

URL的查询字符串...

您在这里实际执行的操作是向带有查询字符串的URL发送POST请求。解析查询字符串并将其放入$_REQUEST$_GET中,与实际使用的HTTP方法无关。但是,$_POST只能用带有请求正文的实际POST请求填充。

在您的fetch()通话中,指定body: formDataformData可以以这种查询字符串格式或其他方式表示。另请参阅:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Body