在脚本中需要帮助

时间:2016-08-19 06:31:16

标签: javascript php jquery ajax

我的脚本代码如下:

function changePrice(id) {
    var url = '<?php echo $base_url ?>home/getprice/';
    $.ajax({
        url: url,
        type: 'post',
        data: 'id='+id,
        success: function(msg) {
            alert(msg); 
            /* 
            "regular_price": "800",
            "discount_price": 720
            */
        }
    });
}

我希望单独变量的正常价格和折扣价格。如何?

3 个答案:

答案 0 :(得分:1)

如果您收到的响应为"regular_price": "800", "discount_price": 720,请将其设为有效JSON,解析并获取属性。

var obj = JSON.parse('{' + msg + '}');
//     valid json    -^-----------^-

// get object properties
var regular  = data.regular_price;
var discount = data.discount_price;

更新:如果响应数据是有效的JSON格式,请设置dataType: 'json'选项。

$.ajax({
    url: url,
    type: 'post',
    data: 'id='+id,
    // set response datatype as json
    dataType:'json',
    success: function(msg) {
        // get properties
        var regular  = msg.regular_price;
        var discount = msg.discount_price;
    }
});

如果响应是字符串,则直接解析。

$.ajax({
    url: url,
    type: 'post',
    data: 'id='+id,
    success: function(msg) {
        // parse the string
        var data = JSON.parse(msg);
        // get properties
        var regular  = data.regular_price;
        var discount = data.discount_price;
    }
});

答案 1 :(得分:0)

试试这个:

在服务器端ajax调用:

$respose['regular_price'] = 120;
$respose['discount_price'] = 100;
echo json_encode($response);

在JS中:考虑msg是一个json对象

var data = JSON.parse(msg);
var regular  = data.regular_price;
var discount = data.discount_price;

答案 2 :(得分:0)

Thanx to all ..这是解决方案:

     <script>
      function changePrice(id)
       {
            var url = '<?php echo $base_url ?>home/getprice/';
            $.ajax({
            url:url,
            type:'post',
            data:'id='+id,
            dataType:'json',
            success:function(msg)
            {
                var regular  = msg.regular_price;
                var discount = msg.discount_price;
            } 
        });
     }
  </script>

我的功能:

  $new = array (
     "regular_price" => $result->price,
      "discount_price" => $price
    );
    $newarray = json_encode($new, JSON_PRETTY_PRINT);
    print_r($newarray);