2013-01-23 42 views
2

我在PHP下面的代碼:爲什麼我不能在Javascript函數中傳遞一個字符串作爲參數?

<?php 
$apples = 123123; 
echo "<td> 
     <input type='button' onclick='confirmation($apples)' value='ac/in'> 
     </td>"; 

echo('<script type="text/javascript"> 
      function confirmation(test) { 
       var answer = confirm("Are you sure?") 
       if (answer){ 
        alert(test); 
        $.get("/index.php?f=func_name_to_call", 
        {name: "John", hobby: "Programming"}, function(data) {}); 
       } 
      } 
</script>'); 
?> 

如果$蘋果是一個數字,則參數被正確地傳遞;但是,當它是一個字符串時,函數confirmation()被破壞。有任何想法嗎?提前致謝。

+1

如果你發送一個字符串,它必須是像這樣對待。引用它。 – Alfabravo

回答

7

如果你想爲字符串中使用下面編輯的代碼

echo "<td><input type='button' onclick='confirmation(\"$apples\")' value='ac/in'></td>"; 

只需使用\轉義雙引號它傳遞參數,它會被視爲一個字符串。

+1

謝謝!一旦時間到來,將標誌着它解決。 :P –

+5

或者,您可以使用'json_encode($ apples)'。如果它是一個字符串,它會爲你引用這個變量。以及讓你傳遞更復雜的數據結構(如關聯數組)到javascript中。 – Supericy

+0

它也會爲你逃脫字符串。 – Supericy

2

是的,你必須使用轉義字符\「\」呼籲確認功能,因爲你是沒有它的字符串轉換成整數轉換雙quotes.therefore一個整數類型參數傳遞整數...

1
<?php 
$apples = 123123; 
?> 
<td> 
    <input type='button' onclick='confirmation(<?php echo $apples?>)' value='ac/in'> 
</td> 

<script type="text/javascript"> 
    function confirmation(test) { 
     var answer = confirm("Are you sure?") 
     if (answer){ 
      alert(test); 
      $.get("/index.php?f=func_name_to_call", 
      {name: "John", hobby: "Programming"}, function(data) {}); 
     } 
    } 
</script> 

你會碰到轉換所有這些'的麻煩到"因爲你通過php附和他們,只是一個建議不要echo他們,使用html標記,只是逃避你php

+0

多麼偉大的建議! –

相關問題