将值从Controller传递到jQuery CodeIgniter

时间:2019-02-07 02:07:43

标签: javascript jquery codeigniter

这是Insert_model

class Insert_model extends CI_Model{
   public function idp(){
   $sql = sprintf("SELECT npd from `dosen`  ORDER BY npd DESC LIMIT 1");
   $query = $this->db->query($sql);
   foreach ($query->result_array() as $key ) {
       $npd1 = $key['npd'];
   }
   $kalimat1 = substr($npd1, 0,3);
   return $kalimat1;
}

这是来自寄存器控制器的功能:

class Register extends CI_Controller{
  public $model;
  public function __construct(){
      parent::__construct();
      $this->load->helper(['url','html']);
      $this->load->database();
      $this->load->model('Insert_model');
      $this->model=$this->Insert_model;
  }
  public function index(){
      $nomor= array('npd' => $this->model->idp());
      echo json_encode($nomor);
  }
}

这是我通过Ajax访问$ nomor值的方式:

$("#status").on("change", function(){
var x = $("#status option:selected").attr("value");
if(x=='mahasiswa'){
    $.ajax({
        url:'<?php echo base_url();?>register/index',
        type: 'POST',
        dataType: 'json',
        success : function(nomor){
            $('#nomor').attr('placeholder',nomor.npd);
        },
    });
});

我希望能够从注册控制器传递$nomor以便在我的jQuery文件中使用它。我尝试在Controller上使用json_encode(),但实际上不起作用。

2 个答案:

答案 0 :(得分:0)

尝试使用控制器: 参考:https://www.codeigniter.com/userguide3/general/models.html

$this->load->model('model_name');
$data['npd'] = $this->model_name->method();
echo json_encode($data);

答案 1 :(得分:0)

尝试一下

public function index(){
      $nomor= array('npd' => $this->model->idp());
      echo json_encode($nomor);
      exit();
  }

我希望这会对您有所帮助