jQuery 调用从视图到 cakePHP 函数

jQuery call from view to a cakePHP function

本文关键字:cakePHP 函数 视图 调用 jQuery      更新时间:2023-09-26

在视图中,我有一个这样的下拉列表:

<div class="input select"><label for="customer">Customer</label><select name="data[Project][customer_id]" id="customer">
<option value="16">Customer1</option>
<option value="17">Customer2</option>
</select>

我试图用jQuery做的是,无论是在页面加载还是下拉选择选项更改时,jquery都会使用给定的选项值调用控制器函数,并从该函数获得预期的回报。以下是控制器部分:

public function getInitials($id){
         $this->autoRender = false;
         if($this->request->is('ajax')){
             $initials = $this->Customer->getInitialsById($id);
                     echo json_encode($initials);
    }}

JQuery不是我擅长的东西,但我做了研究,并试图采用一些类似的功能并使其工作,但没有什么是简单的工作,我觉得我做错了什么。这是jQuery:

    jQuery(document).ready(function($){
        $('#customer').change({
       var initials = "";
       $("select option:selected").each(function(){
            initials = "<?php echo Router::url(array('controller'=>'projects','action'=>'getInitialsById')) ?>"
});
$("div").text( initials );
        });

任何帮助都非常感谢。

您需要正确设置 AJAX 调用:http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.getJSON/

此外,还需要在 AJAX 调用中提供新选择的customer <option>value (id),如 getInitials($id) 函数声明中所定义。请注意,您请求的是getInitials而不是getInitialsById,因为后者前者称为。

最后,我不认为echo会奏效。你需要做$this->response->body(json_encode($initials)); (http://book.cakephp.org/2.0/en/controllers/request-response.html#CakeResponse::body)

在文档加载时调用 AJAX 调用是没有意义的,因为这发生在从下拉列表中选择该选项之前。

因此,要在选择选项后进行 AJAX 调用,请添加以下代码:

$('#customer').change(function(){
    var data = $('#inputEl option:selected').val();
    $.ajax({
        type:'POST',
        async: true,
        cache: false,
        url: <?php echo Router::url(array('controller'=>'projects','action'=>'getInitialsById')) ?>,
        success: function(response) {
            jQuery('[ID OF ELEMENT TO HOLD REPONSE (OPTIONAL)').html(response);
        },
        data: data
    });
    return false;
})

尚未进行测试,但这应该有效。