2012-04-17 134 views
0

我設法讓我的API歌詞代碼正常工作。我所面對的只是一個小問題:當用戶在文本框中輸入歌曲名稱並單擊提交按鈕時,我通過getElementById捕獲該值,然後如何將它附加到下面的URL?如何在此PHP代碼中將文本框值添加到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> 

能否請您糾正我到哪裏,我在這段代碼犯了一個錯誤,高度讚賞在這個論壇的所有幫助! :)

+0

那就沒辦法了..你爲什麼不只是提交表單的頁面,做'... Q =」進行urlencode(?。 $ _POST ['value'])。「&for ...'; – scibuff 2012-04-17 16:12:04

+0

@scibuff:我只是試圖在一個頁面中做到這一點,也嘗試通過JavaScript函數,但想到這樣做..我會嘗試你也建議的方式:)。感謝您的努力:) – Arjit 2012-04-17 16:16:21

+0

然後選項是使用Ajax來獲取內容並將其寫回到html頁面 – scibuff 2012-04-17 16:17:29

回答

0

據我理解你的問題,你需要做的是:

<?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值!

+0

我不知道爲什麼這段代碼沒有工作,但是這是我想要的。它總是從API的結果中返回錯誤代碼,而當我測試它爲特定的歌曲,如我在我的帖子中寫的歌曲時,它通常會返回結果.. – Arjit 2012-04-17 16:58:39

+0

它是否在您的結尾工作? – Arjit 2012-04-17 17:05:22

+0

POST將不會讀取輸入的「id」值。它甚至沒有發送。 – 2012-04-17 19:42:29

-1

刪除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"); 
} 
相關問題