简体   繁体   English

使用fetch()从PHP文件获取JSON

[英]Using fetch() to get JSON from PHP file

I have the following data.php file: 我有以下data.php文件:

$command = $_REQUEST["command"];
$APIKey = "*******************";

if(!isset ($_REQUEST["command"]))
{
    echo "You didn't provide a valid API command";
}
else
{
  switch($command)
  {
    case "get_token" :
      $dataArr = array("token" => "Bearer " . $APIKey);
      echo json_encode($dataArr, JSON_PRETTY_PRINT);
      break;
    default:
      echo "Incorrect API command";
      break;
   }
}

Which mean that I have to provide a specific command in the request in order to get the data. 这意味着我必须在请求中提供特定的命令才能获取数据。 It works fine if I use jQuery's $.getJSON() method: 如果我使用jQuery的$.getJSON()方法,效果很好:

$.getJSON(
  'php/data.php',
  {
    command: "get_token"
  }, (result) => {
    this.myToken = result.token;
  });

However I want to try and use the fetch() method. 但是我想尝试并使用fetch()方法。 So I tried this: 所以我尝试了这个:

fetch('php/data.php', {
  method: "GET",
  mode: "cors",
  cache: "no-cache",
  credentials: "same-origin",
  headers: {"Content-Type": "application/json; charset=utf-8"},
  body: JSON.stringify({command: "get_token"}),

}).then(result => {
  console.log('fetch', result);
  this.myToken = result.token;
})

In this case I'm getting this error message: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body . 在这种情况下,我会收到此错误消息: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body

I tried to use it with POST method, tried with just the body key... Nothing seems to be working. 我尝试将其与POST方法一起使用,仅尝试了body键...似乎没有任何效果。

Any ideas, please? 有什么想法吗?

In this case I'm getting this error message: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body. 在这种情况下,我会收到此错误消息:无法在“窗口”上执行“获取”:使用GET / HEAD方法的请求不能具有主体。

GET requests generally pass data for the query using the query string (and jQuery's getJSON function will encode the data there). GET请求通常使用查询字符串为查询传递数据(jQuery的getJSON函数将在那里编码数据)。

First: Remove the body: 第一:拆下机身:

 body: JSON.stringify({command: "get_token"}), 

Second: Remove the claim that the body contains JSON 第二:删除有关正文包含JSON的声明

 headers: {"Content-Type": "application/json; charset=utf-8"}, 

Third: Encode the data in the query string: 第三:将数据编码在查询字符串中:

 var url = new URL('php/data.php', location); url.searchParams.append("command", "get_token"); var url_string = url.toString() console.log(url_string); fetch(url_string, {/* etc */}) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM