Ajax dos not Work Codeigniter

时间:2016-03-16 18:58:49

标签: jquery ajax codeigniter

我的Ajax请求是这样的,当我点击按钮,发送给我validarData,但永远不会返回完成ajax方法。

$( document ).ready(function(){
    $('#save').on('click', ejecturarAjax);
});

function ejecturarAjax(event)
{   
var jqxhr = $.ajax({ 
    url: "<?php echo base_url(); ?>index.php/padron/validarData", //controller, don´t get any post data, just take the control, and never return anything.
    data: "id="+ '102030', //data what i what to get.
    type: "POST", 
    dataType: "json"    
});

jqxhr.done(function(data) {
    alert(data.id);  //dosn´t work.
});

jqxhr.fail(function(XMLHttpRequest, textStatus, errorThrown) {
    alert( errorThrown ); //don´t show any error.
});

jqxhr.always(function() {
    alert( 'first complete');  //don´t show the alert.
});

event.preventDefault();
};

index.php / padron / validarData,不会从ajax中检索数据:

class Padron extends CI_Controller {

public function index(){
       //Index Page
}

public function validarData()
{

    $id = $this->input->post('id');

    $data["id"] = $id;

    $this->output->set_content_type('application/json');

    $result= json_encode( $data);

    echo $result;
}
}

拜托,帮帮我!!!

1 个答案:

答案 0 :(得分:0)

在视图中声明函数名称
查看

<button id="#save" onclick()="functionName()">Button</button>

然后你可以这样使用。

$( document ).ready(function(){
    function functionName(){
        $.ajax({    
            url: "<?php echo base_url(); ?>index.php/padron/validarData",
            data: "id="+ '102030', 
            type: "POST", 
            dataType: "json" 
          }).done(function(data){
            console.log("done");     
            //here data is the variable that contain the returned result from controller
          }).fail(function(data){
            console.log("hello fail");

          });
    }
});

希望这会对你有所帮助。