【问题标题】:Querying an API with form using GET (PHP:Curl, Javascript)使用 GET (PHP:Curl, Javascript) 使用表单查询 API
【发布时间】:2021-02-12 14:23:04
【问题描述】:

所以问题.. 请耐心等待(我只是在学习)! :)

我有两个文件(index.php / form_get.php)

index.php 文件有一个表单,用于存储用户提交的变量,然后 form_get.php 文件在 URL 中使用该变量来请求 json 文件。但是当我在表单中提交两个字母的国家/地区代码时,我没有得到表单下方的结果,因为我认为我会使用 javascript。

实时表格:

index.php

    <html>
    <head>
    <title>Test Covid Country</title>
    <script src="https://code.jquery.com/jquery-latest.js"></script>
    <script>
      function submit_soap(){
        var cc=$("#covid_country").val();
        $.get("form_get.php",{cc:cc},
        function(data){
          $("#json_response").html(data);
        });
    }
    </script>
    </head>
<body>
  <center>
    <h3>Get Covid Country Travel Data</h3>
     <form>
     Country Code: <input name="covid_country" id="covid_country" type="text" /><br />
      <input type="button" value="Submit" onclick="submit_soap()"/>
    </form>
       <br>-----------
      <div id="json_response"></div>
   </center>
</body>
</html>

form_get.php

<?php

$curl = curl_init();

curl_setopt_array($curl, array(
  CURLOPT_URL => "https://api.traveladviceapi.com/search/".$cc.,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 0,
  CURLOPT_FOLLOWLOCATION => true,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "X-Access-Token:XXXXXXXXXXXXXXXXX"
  ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: javascript php html forms curl


    【解决方案1】:

    form_get.php 文件中,您没有检索到在index.php 文件中传递的数据。您需要将$_GET['cc'] 添加到您的form_get.php 文件的顶部以检索“cc”值。

    <?php
    $cc = $_GET['cc'];
    
    $curl = curl_init();
    
    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://api.traveladviceapi.com/search/".$cc,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "GET",
      CURLOPT_HTTPHEADER => array(
        "X-Access-Token:XXXXXXXXXXXXXXXXX"
      ),
    ));
    
    $response = curl_exec($curl);
    
    curl_close($curl);
    echo $response;
    

    【讨论】:

    • 太棒了 :) 如果对您有帮助,请接受其中一个答案。
    【解决方案2】:

    2 认为我注意到你的代码。

    1. CURLOPT_URL =&gt; "https://api.traveladviceapi.com/search/".$cc., 你的变量末尾有一个点。
    2. 你必须初始化$cc变量$cc = $_GET['cc'];

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-17
      • 2021-12-12
      • 1970-01-01
      • 2014-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多