php - 如何使用 php 输出并在 jQuery 中进行比较?

标签 php jquery

print_r($getPrice) 结果是:$getPrice包含的元素不知道,可以是1个或2个或如下(3个元素)

Array
(
    [0] => Array
        (
            [price_qty] => 2
            [price] => 100.0000

        )

    [1] => Array
        (

            [price_qty] => 5
            [price] => 90.0000
        )

    [2] => Array
        (

            [price_qty] => 8
            [price] => 80.0000

        )

)

jquery代码:get all the input value and make an addition

$(document).ready(function() { //wrap in a document.ready event handler
    $('input').on('keyup', function() { 
        var result = 0;
        $('.liste_couleur_qty li input').each(function() {
            result += parseInt(this.value, 10);
        });
        $('div#qtyvalue').text(result); 
    });
});​

现在,我想将结果与 $getPrice 数组中的 [price_qty] 进行比较。如果结果小于 0,则使用结果乘以 [price](来自 $getPrice 数组)值。

例如:

if result(from the jquery code) < 2, then price= result*110. then $('div#qtyvalue').text(result); change to $('div#qtyvalue').text("the qty is "+result+" the price is "+price);

if between 2--5(contain 5), the price is 100. if between 5--8(not contain 8), the price is 90

怎么做呢?谢谢。

有没有办法将 php 数组放入 javascript 数组中然后进行比较?

最佳答案

使用json_encode PHP 函数将数组 $getPrice 转换为 JSON 字符串。然后将其分配给 JavaScript 变量。

更新:

<?PHP

$getPrice = array(
array("price_qty" => 2,"price" => 100.0000),
array("price_qty" => 4,"price" => 300.0000),
array("price_qty" => 6,"price" => 500.0000)
);

$json = json_encode($getPrice);

?>

在 jQuery 中解析它

<script>
    $(document).ready(function () {
    var parsedData = <?PHP echo $json; ?>;

    for(k in parsedData)
       alert(parsedData[k].price_qty);

    });
</script>

关于php - 如何使用 php 输出并在 jQuery 中进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13490567/

相关文章:

javascript - 获取表单 html 及其值

jQuery:在另一个 jquery 操作后刷新 div?

php - IE 中 HTTPS Ajax 请求的问题(非跨域)

asp.net - 如何从 js 代码显示 CalendarExtender 而不将其用作扩展程序?

php - 使用 getElementById 是否可以实现相同的目的

php - 如何从 JavaScript 访问我的 PHP 变量?

php - 无法更新 Laravel4 中的记录 : SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘id’ in ‘where clause'

php - 使用 Jquery 将数据从 javascript 传递到 php

jquery - 如何使过滤器搜索不区分大小写?

php - 电子邮件管道到 php 脚本仅有时有效