【问题标题】:Update select2 with ajax symfony使用 ajax symfony 更新 select2
【发布时间】:2016-01-04 07:25:43
【问题描述】:

我创建了一个创建新选择选项的表单,现在我想使用 ajax 更新该选择输入类型,这样我就不必重新加载整个页面。

我试过的方法是这样的:

控制器返回这个

return new JsonResponse(['data'=>$em->getRepository('AppBundle:ClasificacionAO')->findAll()]);

而 Ajax 是

$.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function(data) {
             // optionally check if the response is what you wanted
             //if (data.response == 'deleted') {
             //
                      $('select').select2({
                            data: data
                        });

            //also tried with the id: paciente_form_clasificacionAO
            //$('paciente_form_clasificacionAO').select2({
            //                                data: data
            //                            });



             //}
         }
        })

在我刷新整个页面之前,选择选项不会更新,如何修复它以显示创建的新选择选项?

【问题讨论】:

  • 您使用的是哪个 select2 版本?
  • 我使用的是v4.0.1

标签: javascript jquery ajax symfony jquery-select2


【解决方案1】:

我设法解决了这个问题。问题是控制器没有以有效的方式传递数组。之后只是在javascript中使用数据。

        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('AppBundle:ClasificacionAO')->findAll();
        foreach ($entities as $entity) {
            $response1[] = array(
                'key' => $entity->getIdentificadorAO(),
                // other fields
            );
            $response2[] = array(
                'value' => $entity->getId(),
                // other fields
            );
        }

        return new JsonResponse(([$response1,$response2]));

阿贾克斯

    $.ajax({
        type: $(this).attr('method'),
        url: $(this).attr('action'),
        data: $(this).serialize(),
        success: function(data) {

         dataOptions = data[0];
         dataIds     = data[1];

        // Get the raw DOM object for the select box
        select = document.getElementById('paciente_form_clasificacionAO');

        // Clear the old options
        select.options.length = 0;

        // Load the new options
        // Or whatever source information you're working with
        for (var index = 0; index < dataOptions.length; index++) {
          option = dataOptions[index];
          opt1 = document.createElement("option");
          opt1.text = option['key'];

          opt1.value = dataIds[index]['value'];
           //console.log(opt1);

          select.options.add(opt1);
        }

     }
    })

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 1970-01-01
    • 2014-10-18
    • 2016-04-01
    • 1970-01-01
    相关资源
    最近更新 更多