如何使用CodeIgniter正确传递Ajax数据?

时间:2013-09-25 10:44:30

标签: php jquery ajax codeigniter

我想创建一个带复选框的动态地图,以自定义地图上的标记。 当然我使用Ajax,我想用它:)

我的ajax调用没问题,我将视图中的数据传递给控制器​​:

$( "input[type=checkbox]" ).click(function() {
  var data = $(this).val();
  var request = $.ajax({
  type: "POST",
  url: "<?php echo site_url(current_url());?>",
  data: "categorie=" + data,
});
request.done (function(data){
  var json = data;
  // Remove the markers and add new ones

我将数据传递给控制器​​并将其视为

    if ($this->input->is_ajax_request()) {
        $category = $_POST['categorie'];
        $unsigned_url = "http://api.yelp.com/v2/search?location=" . $data->home['city']['cities_name'] . "&category_filter=" . $category;
        $new_JSON = $this->listing_lib->getJsonFromYelp($unsigned_url);
        echo $new_JSON;
    }

问题是,在JS的json变量中,我从PHP获得了JSON,但是我也得到了页面的所有DOM? 为什么 ?我怎么才能得到我的JSON?

4 个答案:

答案 0 :(得分:0)

 $( "input[type=checkbox]" ).click(function() {
    var data = $(this).val();
    $.ajax({
      type: "POST",
      url: "<?php echo site_url(current_url());?>",
      data: {"categorie":data},
      dataType:"json",
      cache: false
      success: function (categorie) {
        /// your code for show category
     }
    });

答案 1 :(得分:0)

if ($this->input->is_ajax_request()) {
    $category = $_POST['categorie'];
    $unsigned_url = "http://api.yelp.com/v2/search?location=" . $data->home['city']['cities_name'] . "&category_filter=" . $category;
    $new_JSON = $this->listing_lib->getJsonFromYelp($unsigned_url);
    header('Content-type: application/json');
    print_r json_encode($new_JSON);
}

这应该更好。

答案 2 :(得分:0)

请试试这个

$( "input[type=checkbox]" ).click(function() {
       var data = $(this).val();
       var request = $.ajax({
       type: "POST",
       url: "<?php echo site_url(current_url());?>",
       data: "categorie=" + data,
       dataType:"json",
       success:function(response){
         alert(response);

       }
});

并在控制器中

if ($this->input->is_ajax_request()) {
    $category = $_POST['categorie'];
    $unsigned_url = "http://api.yelp.com/v2/search?location=" . $data->home['city']['cities_name'] . "&category_filter=" . $category;
    $new_JSON = $this->listing_lib->getJsonFromYelp($unsigned_url);
    print json_encode($new_JSON);
}

我希望这会对你有所帮助。

答案 3 :(得分:0)

在输出json之前尝试设置输出类型和输出:

    if ($this->input->is_ajax_request()) {
            $category = $_POST['categorie'];
            $unsigned_url = "http://api.yelp.com/v2/search?location=" 
            .$data->home['city']['cities_name'] . "&category_filter=" . $category;

            $new_JSON = $this->listing_lib->getJsonFromYelp($unsigned_url);
            $this->output->set_content_type('application/json'); 
            $this->output->set_output($new_JSON);  
    }