选择选项,然后根据选中的's选项进行Ajax/PHP刷新


Select option, then Ajax/PHP refresh regarding to the selected's option

我快疯了。我有一个不同值的select选项。它们需要每秒作为POST ajax请求发送到一个PHP文件,并打印输出。ajax调用工作正常,我只是无法处理select上。变化的功能。有人能帮帮我吗?

index . html

<html>
    <head>
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
        <script type="text/javascript">
            var currency = '';
            $('#currency').on('change', function () {
                currency = this.value;
                reload_script()
            });
            function repeatAjax() {
                jQuery.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    data: { 'currency': currency },
                    dataType: 'text',
                    success: function (e) {
                        $('#output').html(e)
                    },
                    complete: function () {
                        setTimeout(repeatAjax, 1000)
                    }
                })
            }
            repeatAjax()
        </script>
    </head>
    <body>
        <b>Please select currency: </b>
        <br />
        <select name="currency" id="currency">
            <option value="">-- Please Select --</option>
            <option value="BTC/USD">BTC/USD</option>
            <option value="BTC/EUR">BTC/EUR</option>
            <option value="BTC/GBP">BTC/GBP</option>
        </select>
        <br />
        <b>Result: </b>
        <div id="output"></div>
    </body>
</html>

ajax.php

<?php
if(isset($_POST['currency'])) {
    switch($_POST['currency']) {
        case 'BTC/USD':
            echo 'Current currency of BTC/USD: 0.000 / 0.000';
            break;
        case 'BTC/EUR':
            echo 'Current currency of BTC/EUR: 0.000 / 0.000';
            break;
        case 'BTC/GBP':
            echo 'Current currency of BTC/GBP: 0.000 / 0.000';
            break;
        default:
            echo 'Please select currency first.';
            break;
    }
}
?>

我想这就是你想要的:

var currency = '';
            $('#currency').on('change', function () {
                currency = $( this ).val(); // <-----------this has been changed
                repeatAjax(); // <----- this function has changed 
            });
            function repeatAjax() {
                jQuery.ajax({
                    type: 'POST',
                    url: 'ajax.php',
                    data: { 'currency': currency },
                    dataType: 'text',
                    success: function (e) {
                        $('#output').html(e)
                    },
                    complete: function () {
                        setTimeout(repeatAjax, 1000)
                    }
                })
            }
            repeatAjax()