2016-08-19 272 views
-3

像我的腳本代碼:需要幫助腳本

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 
      */ 
     } 
    }); 
} 

我想在不同的variable.How雙方正價和折扣價?

+0

什麼是味精? console.log(msg),然後檢查控制檯。 –

+1

'msg.regular_price'和'msg.discount_price'不適合你嗎? –

+0

是的,如果味精是一個對象,我同意@Swaraj Giri –

回答

0

試試這個:

在服務器端AJAX調用:

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

在JS:考慮味精是一個JSON對象

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

語法錯誤:JSON.parse:位於第1行的JSON數據 –

+0

成功的第1列意外的字符:函數(MSG) \t \t \t \t { \t \t \t \t \t變種newdata = JSON.parse(MSG); \t \t \t \t \t var regular = newdata.regular_price; \t \t \t \t \t var discount = newdata。折扣價; \t \t \t \t \t alert(regular); \t \t \t \t \t \t \t \t \t} –

+0

手段消息的返回類型不是一個JSON對象 –

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; 

UPDATE:如果響應數據是有效的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; 
    } 
}); 
+0

O/P: \t { \t \t 「REGULAR_PRICE」: 「50」, \t \t 「discount_price」: 45 \t} success:function(msg) { \t var obj = JSON.parse('{'+ msg +'}'); \t var regular = data.regular_price; \t var discount = data.discount_price; \t alert(regular); } // SyntaxError:JSON.parse:預期屬性名稱或'}'在JSON數據的第1行第2列 –

+0

@ZuberMafat檢查更新的代碼 –

0

感謝名單以all..Here是解決方案:

 <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);