2017-08-13 173 views
-1

如何從響應中提取值? 警報輸出是[{「maturitydays」:「120」}] 我只想要價值!我如何獲得價值?

$("#selectCrop").change(function(){ //this ajax will bring default configured crop data 
    var cropid = $("#selectCrop option:selected").val(); 
    var url = "<?php echo base_url();?>index.php/user/cropConfig/getData"; 
    $.ajax({ 
     data : {'cropid':cropid}, 
     type : 'post', 
     url  : url, 
     success :function(response) { 
      alert(response); 
     } 
    }) 
}); 
+0

@MaximShoustin其實它是一個數組,因此:'響應[0] .maturitydays' –

+0

@ErenTantekin是的,它應該採取0項目第一 –

回答

0

這是json。

使用json_decode使其成爲數組,然後從數組中獲取值(如果必須的話)。

$array = json_decode('{"maturitydays":"120"}',true); 
$value=$array["maturitydays"]; 
Echo $value; 

https://3v4l.org/Uc51m

2

看來你的反應是一個數組內由於方括號,這意味着你需要通過獲得的值:

response[0]['maturitydays'] 

所以您的代碼將是這樣的:

$("#selectCrop").change(function(){ //this ajax will bring default configured crop data 
           var cropid = $("#selectCrop option:selected").val(); 
           var url = "<?php echo base_url();?>index.php/user/cropConfig/getData"; 
            $.ajax({ 
            data : {'cropid':cropid}, 
            type : 'post', 
            url  : url, 
            success :function(response) { 
             alert(response[0]['maturitydays']); 
            } 
            }) 
           }); 
+1

響應[0] [「maturitydays」]是這樣的反應[0] ['maturitydays']謝謝爲你的幫助這是有幫助的 – Talha

0

作爲響應得到的數據是JSON array的數量爲JSON objects。 JSON(JavaScript對象表示法)可以立即用作JavaScript object(只要它不在string表單中,在這種情況下必須使用JSON.parse進行解析)。
當收到響應可以像使用一個常規的JavaScript陣列(如果你確定其永遠只有1個對象,則可以選擇第一個索引馬上)訪問它:

let obj = response[0]; 

當得到的對象,只是獲得你想要,你會與一個正常的JavaScript對象的值:

let val = obj.maturitydays;