将数据发送到'view'而不加载它

时间:2013-10-11 11:21:59

标签: javascript php ajax codeigniter

这是否可以在不加载数据的情况下发送数据? 我在谷歌地图库工作codeigniter。我有在列表页面上列出酒店的情况,当用户点击地图时,它会加载显示该地址的谷歌地图。我使用ajax在控制器中调用函数。问题是输出有2种类型的数据。一个应插入页面的head,另一个插入特定body中的div.

echo $map['html'];
echo $map['js'];

html应插入div,而'js'插入头部。两者都是按功能输出并返回响应Ajax。

ajax调用的view文件已被另一个函数加载。如何处理?

查看文件(Ajax功能)

function showMap(id)
{
var detail_id = id.replace('map_','detail_desc_');
var hotel_id = id.replace('map_','');

$("#detail_map_"+hotel_id).html('loading');

$("#"+detail_id).slideDown('fast');

    var data = hotel_id;
    $.ajax({
        url:'<?php echo base_url() . "hotels/getMap";?>',
        data:'id='+data,
        type:'get',
        cache: false,
        success: function(data) {
            alert(data);
            //$("#detail_map_"+hotel_id).html(data);
        }//end success
    });//end ajax   
}

控制器功能

public function getMap()
{
    $id = $_GET['id'];
    $map_config['directions'] = true;
    $map_config['center'] = 'G 11 Markaz, Islamabad Pakistan';
    // Initialize our map. Here you can also pass in additional parameters for customising the map (see below) 
    $this->googlemaps->initialize($map_config);


    // Set the marker parameters as an empty array. Especially important if we are using multiple markers
    $marker = array();
    // Specify an address or lat/long for where the marker should appear.
    $marker['position'] = 'G 11 Markaz, Islamabad Pakistan'; 
    $this->googlemaps->add_marker($marker);

    // placed where we want the map to appear.
    $data['map'] = $this->googlemaps->create_map();

    //print_r($data['map']);

    echo $data['map']['html'];

            echo $data['map']['js'];

            //these two echos are sent back in response to ajax function
}

现在我想将echo $data['map']['js'];放在head标签中,而另一个body放在div内。

1 个答案:

答案 0 :(得分:1)

如果问题是将此返回的数据放在您调用getMap()的视图中,则可以在控制器中执行此操作:

$json = array(
  'html' => $data['map']['html'],
  'js' => $data['map']['js']
);

echo json_encode($json);

然后在JavaScript回调中使用它们:

$.ajax({
    url:'<?php echo base_url() . "hotels/getMap";?>',
    data:'id='+data,
    dataType: 'json',
    type:'get',
    cache: false,
    success: function(data) {
        $("#yourdiv").html(data.js);
        $("#yourdiv").append(data.html);
    }//end success
});//end ajax  

寻找我所做的改变。由于这会产生问题,我建议将data.js放在div中,因为每次加载地图时,如果它在{{1}中,它会一次又一次地追加这些返回的数据}}。这样,它首先会转储您的head,然后将divdata.js添加到其中。