首页 > 解决方案 > jQuery 提取令牌并将其传递给 php 位置标头

问题描述

我想使用 jQuery 从 API 中提取令牌,然后将其传递给 URL 中的 php 位置标头参数。

例子:

<script>
$.getJSON('https://example.com/APIENDPOINT', function(data) {
    alert(data.access_token)
});
</script>

<?php
header('Location: https://example.com/auth/?access_token=${data.access_token}');
?>

我不确定我做错了什么,如果有人可以给我任何提示,我会很高兴。

标签: javascriptphpjquery

解决方案


可能是这样的:

$.getJSON('https://example.com/APIENDPOINT', function(data) {
    window.location.href = 'https://example.com/auth/?access_token=' + data.access_token;
});

如果需要 301 重定向,则仅在服务器端运行(php)

<?php
  $json = file_get_contents('https://example.com/APIENDPOINT');
  $obj = json_decode($json);
  $token =  $obj->access_token; 
  $url = 'https://example.com/auth/?access_token=' . $token ; 
  header("Location: ".$url, true, 301);
  exit();
?>

推荐阅读