简体   繁体   中英

How to pass json encoded results from controller to javascript variable

I want to pass json encoded array results from codeigniter controller to javascript variables in view

$.ajax
 ({
  type:'post',
  url: "<?php echo base_url(); ?>" +"",
  data:{
   d_name:d_name,
   d_password:d_password,
   dataType:"json",
  },
  success: function(result) {
    var obj = parseJSON(result);
    var u = obj.d_name; 
    var v = obj.d_password; 
    alert(v);
},
error: function() { 
  alert("error");
}
 });  

my output from controller is here:

string(61) "[{"id":"1","doc_id":"1","d_name":"done","d_password":"done"}]" 

i want to assign value of d_name and d_password to javascript variable to verify

Controller code:-

$data['result']=$this->Clinic_model->d_login($d_credentials); 
$result = json_encode($data['result']); 
var_dump($result);die;

1.Put dataType:"json", outside of data .

2. var obj = parseJSON(result); is not required.

3.Now you have array object assign the value.

You need to do like below:

$.ajax({
    type:'post',
    url: "<?php echo base_url(); ?>",
    data:{
        d_name:d_name,
        d_password:d_password
    },
    dataType:"json",
    success: function(result) {
        var u = result[0].d_name; 
        var v = result[0].d_password; 
        alert(v);
    },
    error: function() { 
        alert("error");
    }
});

And use echo in your controller code:

$data['result']=$this->Clinic_model->d_login($d_credentials); 
echo $result = json_encode($data['result']);die;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM