1

所以我试图实现这一点: https ://github.com/phalcon/cphalcon/wiki/Dependent-Select-Dropdown

我让一切正常,它创建选择,填充第一个选择,当我选择一个值时,当我在控制器中调用 grabStatesAction 时,它正确返回如下值:

[{"id":"2","name":"Section1"},{"id":"24","name":"Section2"}"}]

但是,如果我在 javascript 中提醒响应,它根本不会返回,而是从页面返回一堆 HTML。

这是我的脚本

<script type="text/javascript">
    $("#id_product").change(function() {
            var value = $(this).val();

            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: '/admin/section/grabSection/',
                data: {"id": value},
                success: function(response){
                    $("#selectSection option")
                        .not(":first").remove();

                    alert(response);
                    parsed = $.parseJSON(response);


                    $.each(parsed, function(key, value) {
                        $("#selectSection")
                            .append($("<option></option>")
                            .attr("value",value.id)
                            .text(value.name));
                    });
                }
            });
        });
</script>

这是控制器

public function grabSectionAction()
    {
        $id=2; //hardcoded for testing purposes
        $data = Sections::find(array(
            'columns' => array('id_section, section'),
            'conditions' => 'active = 1 AND id_section = :id:',
            'bind' => array('id'=>$id)
        ));
        $resData = array();
        foreach ($data as $result) {
            $resData[] = array("id"=>$result->id_section, "name"=>$result->section);
        }

        echo json_encode($resData);
    }

带有选择的页面是一个带有表单的模式窗口。我在想也许该页面应该将应用程序类型设置为 json,也许这就是问题所在,但如果我这样做,那么表单将会中断。我确实将javascript中的应用程序类型设置为json。任何想法我做错了什么,或者您需要任何具体的附加信息,请告诉我

4

1 回答 1

2

试试下面.. 使用Console.log而不是警报来查看完整的响应字符串。更多信息:https ://developer.chrome.com/devtools/docs/console-api

public function grabSectionAction()
{
    $this->view->disable();

    //Create a response instance
    $response = new \Phalcon\Http\Response();

    $id = 2; //hardcoded for testing purposes
    $data = Sections::find(array(
        'columns' => array('id_section, section'),
        'conditions' => 'active = 1 AND id_section = :id:',
        'bind' => array('id' => $id)
    ));
    $resData = array();
    foreach ($data as $result) {
        $resData[] = array("id" => $result->id_section, "name" => $result->section);
    }

    //Set the content of the response
    $response->setContent(json_encode($resData));

    //Return the response
    return $response;
}
于 2015-08-18T04:01:41.887 回答