【问题标题】:Basic Qn using AJAX jQuery?使用 AJAX jQuery 的基本 Qn?
【发布时间】:2011-10-18 01:41:31
【问题描述】:

我刚开始学习使用 AJAX 和 Codeigniter。在我看来,我有一个 textarea 和一个按钮,它使用 AJAX 将 textarea 中的文本提交给我的控制器,该控制器从数据库中检索数据并将这些数据返回给视图。但是,我在回调函数中收到错误“不允许的键字符”。即使我只是 echo 一个字符串,也会发生这种情况。发生了什么?

顺便说一句,我应该在控制器中使用return $result 还是echo $result 将数据传回网页?

AJAX

$(function() {
    $("#search_button").click(function(e){
        e.preventDefault();
        var search_location = $("#search_location").val();
        $.get('index.php/main/get_places', search_location, function(data){
            $("#result").html(data);
            console.log(data);
    });
});

});

控制器

function get_places($address) {

    $search_latlng = $this->geocode_address($address);
    $this->load->model('main_model.php');
    $result = $this->main_model->get_places($search_latlng);

    echo "test";
}

【问题讨论】:

    标签: php javascript jquery ajax codeigniter


    【解决方案1】:

    CodeIgniter 已将 url 中的字符限制为:

    $config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-'; //Inside config.php
    

    当您发送 AJAX 请求时,您可能会在地址中输入不在此列表中的字符。我的建议是将$.get 更改为$.post,然后在控制器中获取发布数据。像这样的:

    AJAX

    $(function() {
        $("#search_button").click(function(e){
            e.preventDefault();
            var search_location = $("#search_location").val();
            $.post('index.php/main/get_places', {'search_location': search_location}, function(data){
                $("#result").html(data);
                console.log(data);
            });
        });
    });
    

    控制器

    function get_places() {
        $address = $this->input->post('search_location');
        $search_latlng = $this->geocode_address($address);
        $this->load->model('main_model.php');
        $result = $this->main_model->get_places($search_latlng);
    
        echo $result;
    }
    

    对于echo 与return,使用echo。

    【讨论】:

      【解决方案2】:

      您可能不允许在 URL 中使用查询字符串,并且 Ajax 函数将查询字符串添加到 url。查看以下 url 以了解如何打开查询字符串:

      http://www.askaboutphp.com/58/codeigniter-mixing-segment-based-url-with-querystrings.html

      【讨论】:

        猜你喜欢
        • 2016-01-01
        • 2014-08-07
        • 2018-09-24
        • 1970-01-01
        • 2012-03-30
        • 1970-01-01
        • 2011-07-27
        相关资源
        最近更新 更多