将jquery变量作为参数传递给php函数

时间:2016-07-23 06:57:15

标签: php jquery

$("#slider-range-max-day-count").slider({
                range: "max",
                min: 1,
                max: 365,
                value: 1,
                animate: "fast",
                slide: function (event, ui) {
                    $("#dayCount").text(ui.value);
                    var invPackageValue = $('#investmentPackage').text();
                    var dayValue = ui.value;
                    <?php
                    $compoundInterest = $CI->compound_int($package, $day, $interest_rate->static_interest);
                    ?>
                    $("#sliderResult").text(<?php echo $compoundInterest;?>);
                }
            });

在函数$CI->compound_int($package, $day, $interest_rate->static_interest);中,如何传递invPackageValue和dayValue而不是$package$day参数。

1 个答案:

答案 0 :(得分:1)

你应该ajax调用在php中使用javascript变量。在ajax调用的请求中传递javascript变量。然后我们可以在这些变量的php文件中获取值并在php文件中执行该函数并返回输出,在ajax success函数中我们可以获得响应。

// Javascript + Jquery代码。

<script type="text/javascript">
    $("#slider-range-max-day-count").slider({
        range: "max",
        min: 1,
        max: 365,
        value: 1,
        animate: "fast",
        slide: function (event, ui) {
            $("#dayCount").text(ui.value);
            var invPackageValue = $('#investmentPackage').text();
            var dayValue = ui.value;
            $.ajax({
                url : 'PATH OF SAME FILE',
                data : 'package='+invPackageValue+'&day='+dayValue,
                type : 'post',
                dataType : 'json',
                success : function(data){
                    $("#sliderResult").text(data.compoundInterest);
                }
            });         
        }
    });
</script>

// PHP代码

<?php
    if(isset($_POST['package'])){
        $compoundInterest = $CI->compound_int($package, $day, $interest_rate->static_interest);
        echo json_encode(['compoundInterest'=>$compoundInterest]);exit;
    }
?>