如何从ajax函数(PHP)为js变量赋值

时间:2014-04-17 07:55:44

标签: javascript php jquery ajax

我有以下ajax

function loadCalender() {
    $.ajax({
        url: '<?php echo base_url()."catering"."/"."loadStoreCalender"; ?>',
        method: 'POST',
        data: {
            val: $(this).val()
        },
        context : this,
        success: function(result) {
            // I have to Assign value to Array in the following format
        //events[0] = { Title: "Booking Not Available", Date: new Date("05/13/2014") };
        //events[1] = { Title: "Booking Not Available", Date: new Date("04/21/2014") };
        //events[2] = { Title: "Booking Not Available", Date: new Date("04/22/2014") };
        //events[3] = { Title: "Booking Not Available", Date: new Date("04/23/2014") };
        }
    });
    return false;
}

我的问题是如何将数组值从PHP控制器传递到Ajax以实现所需格式的数组(我的意思是“

`//events[0] = { Title: "Booking Not Available", Date: new Date("05/13/2014") };`

“)。

以下是我的PHP控制器

public function loadStoreCalender()
    {
        $this->load->model('catering_model');
        $result=array();//???
        $storeId = $_POST['val'];
        $result = array("Title" => "Booking Not Available","Date" => new Date("04/21/2014")); // For Example
        die(json_encode($result));
    }

我正在使用PHP CI和Ajax为Booking System创建一个函数。我在使用数组和ajax的东西是noob。请帮帮我。

先谢谢了。

2 个答案:

答案 0 :(得分:1)

试试这个:

function loadCalender(callback) {
    $.ajax({
        url: '<?php echo base_url()."catering"."/"."loadStoreCalender"; ?>',
        method: 'POST',
        data: {
            val: $(this).val()
        },
        dataType: 'json',
        context : this,
        success: function(results) {
            callback(results);
        }
    });
    return false;
}

// Test
loadCalender(function(eventsJsonObjArray)
{
    console.log(eventsJsonObjArray);
});

答案 1 :(得分:0)

function loadCalender(callback) {
    $.ajax({
        url: '<?php echo base_url()."catering"."/"."loadStoreCalender"; ?>',
        method: 'POST',
        data: {
            val: $(this).val()
        },
        dataType: 'json',
        context : this,
        success: function(results) {
            callback(results);
        }
    });
    return false;
}

// Test
loadCalender(function(eventsJsonObjArray)
{
    console.log(eventsJsonObjArray);
});