4

jQuery で php 値を使用するにはどうすればよいですか?、私が行っているのは、次のように php を使用してデータベースから付加価値税率を取得し、 $vatrate に格納することです。

$sqlv = <<<SQL
SELECT *
FROM   `vatrate`
WHERE  id='1'
SQL;
if(!$resultv = $db->query($sqlv)){
  die('There was an error running the query [' . $db->error . ']');
}
while($rowv = $resultv->fetch_assoc()){
    $vatrate =  $rowv['vatrate'];
} ?>

次に、すべての行の合計を合計してスパンに入れる jQuery スクリプトを作成します。

<script>
$(document).ready(function() {
    $('input').on('keyup', function() {
        var rawValue, grandtotal = 0;
        $('span[id^="linetotal"]').each(function(i, elem) {
            rawValue = $.trim($(this).text());
            if (rawValue == '') rawValue = 0;
            grandtotal += parseFloat(rawValue);
        });
        $('#grandtotal').text(grandtotal);
    });
});
</script>

しかし、php で宣言された $vatrate 値を jQuery で参照する方法がわからないため、価格 + 付加価値税を取得できます。VAT は、英国以外の人の消費税です :) 。

4

3 に答える 3

0

変数を Javascript にエコーする場合、引用符を省略して float としてキャストできます。これは、Javascript 変数が float であることを意味し、計算のために使用する準備ができていることを意味します。float としてキャストすると、クロス サイト スクリプティング (XSS) の可能性も防止されます。

<script>
var vatRate = <?php echo (float)$vatrate; ?>;

$(document).ready(function() {
    $('input').on('keyup', function() {
        var rawValue, grandtotal = 0;
        $('span[id^="linetotal"]').each(function(i, elem) {
            rawValue = $.trim($(this).text());
            if (rawValue == '') rawValue = 0;
            grandtotal += parseFloat(rawValue);
        });

        // add the vat to the grandtotal
        // assuming vatRate is 20 for 20%, not 0.2
        grandtotal += (grandtotal * (vatRate / 100));
        $('#grandtotal').text(grandtotal);
    });
});
</script>
于 2013-07-02T13:40:37.360 に答える