微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将AJAX参数传递给extbase操作?

现在我设法从数据库获取值,我想指定更多我想要传递的内容.

从对下面的事件函数作出反应的选择框中,我想读出一个值(记录的uid)并将其传递给我的ajaxAction:


    

var uid;
    $('#mySelectBox').change(function() {
        arguments = $(this).attr('value');
        var uri = '<f:uri.action arguments="{uid: '+uid+'}" action="ajax" controller="Mycontroller1" pageType="89657201" />';

        jQuery.getJSON(uri,function(result) {
            // do something
        });
    });

我用参数试了一下,不知道这是不是正确的方法.另外,正如marcus Biesioroff建议的那样,我应该将我的JS保存到一个单独的文件中,但是我必须自己编写uri而不是Fluid方式,对吧?

我的ajaxAction看起来像这样:


    

public function ajaxAction($uid) {
            $dataFromrepo = $this->myRepository->findByUid($uid);

            $resultArray = array(
                "field1" => $dataFromrepo->getField1(),"field2" => $dataFromrepo->getField2(),"field3" => $dataFromrepo->getField3(),"field4" => $dataFromrepo->getField4(),);
            return json_encode($resultArray);
        }

我确信uid没有正确传递,其他一切都有效.

解决方法

有一些错误

>你不能用JS破坏vievhelper的语法,即使它被置于视图中,你需要从< f:uri.action />中传递完整的动作路径.
>你不能把这个JS放在视图中,因为它包含大括号,那里有other description of the issue
>你需要从外部文件调用ajax函数并分别传递给它的action链接和uid,然后添加

在视图中:

<script type="text/javascript">
    var actionsPathFromViewHelperSetInTheView 
        = '<f:uri.action action="ajax" controller="Mycontroller1" pageType="89657201" />';
</script>
<script type="text/javascript" src="path/to/ext/Public/yourExternal.js"></script>


<!-- of course this field may/should be created with Fluid's viewhelper -->
<select id="mySelectBox" onchange="performAjaxCall(this)">
    <option value="1">Item 1</option>
    <option value="2">Item 2</option>
    <option value="3">Item 3</option>
</select>

在yourExternal.js中(当然你需要将tx_yourextkey_yourplugin前缀更改为你自己的)

function performAjaxCall(selectFieldobj) {
    $.ajax({
        url: actionsPathFromViewHelperSetInTheView,data:{
            "tx_yourextkey_yourplugin[uid]":selectFieldobj.value
        },success:function (data) {
            // do something with your json
            alert('Load was performed.');
        }
    });
}

在你的控制器中:

public function ajaxAction() {

    // try to always validate the incoming arguments
    if (!$this->request->hasArgument('uid') || intval($this->request->getArgument('uid')) == 0) {
        header('HTTP/1.1 400 Bad Request');
        return json_encode(array('error'=> 'Bad request'));
    }

    $uid = intval($this->request->getArgument('uid'));

    $dataFromrepo = $this->myRepository->findByUid($uid);
    if ($dataFromrepo == null) {
        header('HTTP/1.1 404 Not found');
        return json_encode(
           array('error'=> 'Not found or you have no access or something else... happens...')
        );
    }
    $resultArray = array(
        "field1" => $dataFromrepo->getField1(),// etc...
    );

    return json_encode($resultArray);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐