Javascript 在使用PHP调用API后,如何在sessionStorage中存储会话数据?

Javascript 在使用PHP调用API后,如何在sessionStorage中存储会话数据?,javascript,php,session,Javascript,Php,Session,因此,我使用PHP调用了一个API,代码如下: $url_get_fc = 'http://apiurlhere'; //Send the request $response_fc = curl_exec($ch_fc); curl_close($ch_fc); //Check for errors if($response_fc === FALSE){ die(curl_error($ch_fc)); } // Decode the response $responseData_fc

因此,我使用PHP调用了一个API,代码如下:

$url_get_fc = 'http://apiurlhere'; 

//Send the request
$response_fc = curl_exec($ch_fc);
curl_close($ch_fc);

//Check for errors
if($response_fc === FALSE){
 die(curl_error($ch_fc));
}
// Decode the response
$responseData_fc = json_decode($response_fc, TRUE);

// sessionStorage

sessionStorage.setItem(responseData_fc);

console.log(set);

现在,我尝试将API传递的json文件存储在浏览器的sessionStorage中。这可能吗?因为我知道SessionToAge是javascript,所以不太确定如何将其存储在浏览器中?希望有人能告诉我要在浏览器上使用会话存储,您必须使用javascript,这是一种在客户端(浏览器)上执行的语言,php是一种将在服务器端执行的语言,因此无法满足您的需要

要修复您的示例,您可以:

  • 使用php调用API并将结果发送给分配给一个变量的客户端,这样就可以从SessionStorage中存储的javascript ans中读取结果
  • 使用javascript来执行对API的调用,这样以后性能问题就会减少
  • 我还建议您阅读@jon stirling所指出的关于客户端/服务器端差异的内容

    使用您的代码,案例1的一个示例可能是:

    $url_get_fc = 'http://apiurlhere'; 
    
    //Send the request
    $response_fc = curl_exec($ch_fc);
    curl_close($ch_fc);
    
    //Check for errors
    if($response_fc === FALSE){
     die(curl_error($ch_fc));
    }
    // Decode the response
    $responseData_fc = json_decode($response_fc, TRUE);
    
    // sessionStorage
    
    echo '
    <html><head>
    <script type="text/javascript">
        alert("'.$responseData_fc.'");
    </script>
    </head><body></body></html>';
    
    $url\u get\u fc=http://apiurlhere'; 
    //发送请求
    $response\u fc=curl\u exec($ch\u fc);
    卷曲关闭($CHU fc);
    //检查错误
    如果($response_fc==FALSE){
    模具(卷曲误差($ch_fc));
    }
    //解码响应
    $responseData_fc=json_decode($response_fc,TRUE);
    //会话存储
    回声'
    警报(“.$responseData_fc.”);
    ';
    
    我可以只使用一个PHP文件来完成数字1吗?我希望能在PHP代码中插入一个javascript片段?对不起,我不太确定如何前进:(答案更新,为什么这样,如果答案是正确的,请标记为正确答案。