如何在此PHP代码中捕获和追加文本框值到URL


How to catch & append a textbox value to a URL in this PHP code?

我设法让我的API歌词代码工作。我面临的只是一个小问题:当用户在文本框中输入歌曲名称并单击提交按钮时,我通过getElementById捕获值,然后如何用下面的URL附加它?

这是我的代码:

<?php
     //Catches the value of the Submit button: 
     $submit = isset($_POST['submit']);
     if($submit) {
?>
     <script type="text/javascript">
         var val1 = document.getElementById('val').value;
     </script>
<?php
    /* The below $res contains the URL where I wanna append the caught value. 
       Eg: http://webservices.lyrdb.com/lookup.php?q=Nothing Else Matters(Or 
       what the user searches for)&for=trackname&agent=agent
    */
      $res = file_get_contents("http://webservices.lyrdb.com/lookup.php?q='+val1+' &for=trackname&agent=agent");
?>
<html>
   <form method="post" action="">
      Enter value: <input type="text" name="value" id="val" /><br/>
      <input type="submit" value="Submit" name="submit" />
   </form>
</html>

您能否纠正我在这一段代码中犯错的地方,非常感谢此论坛中的所有帮助! :)

据我了解您的问题,您需要做的是:

<?php
     //Catches the value of the Submit button: 
     $submit = isset($_POST['submit']);
     if($submit) {
     $val1 = $_POST['val'];    // TO store form passed value in "PHP" variable.
    /* The below $res contains the URL where I wanna append the caught value. 
       Eg: http://webservices.lyrdb.com/lookup.php?q=Nothing Else Matters(Or 
       what the user searches for)&for=trackname&agent=agent
    */
      $res = file_get_contents("http://webservices.lyrdb.com/lookup.php?q=' . urlencode($val1) . ' &for=trackname&agent=agent");
   }   // This is to end the "if" statement
?>

,然后将表单输入字段更改为:

      Enter value: <input type="text" name="val" id="val" /><br/>

我不确定 POST 是否也接受id值!

删除 javascript 这是不必要的。PHP 在服务器上运行客户端的 Javascript

然后将您的 PHP 代码更改为以下内容:

if(isset($_POST['value'])) {
    $res = file_get_contents("http://webservices.lyrdb.com/lookup.php?q=". $_POST['value'] ." &for=trackname&agent=agent");
}