Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将php变量从select传递到jquery?_Php_Jquery_Laravel - Fatal编程技术网

如何将php变量从select传递到jquery?

如何将php变量从select传递到jquery?,php,jquery,laravel,Php,Jquery,Laravel,我有下一个代码来加载我网站中的所有国家/地区: $document.readyfunction{ $.ajax{ 键入:“GET”, url:“/comunidades”, 成功:功能响应{ $cbx_comunidad.empty; //console.logresponse; $cbx_comunidad.Prependselecione comunidad; 对于i=0;i 这可能是因为有一个触发器将我的php变量传递给我的jquery代码?如何选择我的默认值来更新视图?我应该能够在标记中

我有下一个代码来加载我网站中的所有国家/地区:

$document.readyfunction{ $.ajax{ 键入:“GET”, url:“/comunidades”, 成功:功能响应{ $cbx_comunidad.empty; //console.logresponse; $cbx_comunidad.Prependselecione comunidad; 对于i=0;i
这可能是因为有一个触发器将我的php变量传递给我的jquery代码?如何选择我的默认值来更新视图?

我应该能够在标记中打印经过净化的php数据,如下所示

<label for="cbx_comunidad">Seleccione Comunidad:</label>
<select onload="setDefault('<?php echo htmlentities($user->comunidad_id, ENT_QUOTES, 'UTF-8'); ?>')" class="form-control @error('cbx_comunidad') is-invalid @enderror" name="cbx_comunidad" id="cbx_comunidad" required>
</select>

在加载文档时,您正在填充select from ajax,但在加载select元素时尝试设置所选值。这意味着select为空,此时没有可匹配的选项。 您应该在添加/附加所有选项后尝试执行选择。因此,在选择中,使用数据id存储所选值,并在附加所有选项后读取此值以预选选项

$(document).ready(function() {
  $.ajax({
    type: 'GET',
    url: '/comunidades',

    success: function(response) {
      $("#cbx_comunidad").empty();
      // console.log(response);
      $("#cbx_comunidad").prepend("<option value='' selected='selected'>Seleccione Comunidad</option>");
      for (i = 0; i < response.length; i++) {
        $("#cbx_comunidad").append("<option value='" + "rellena una opcion" + "</option>");
        //console.log('response' + response[i].id);
        $("#cbx_comunidad").append("<option value='" + response[i].id + "'>" + response[i].comunidad + "</option>");
      }

      $("#cbx_comunidad").val($("#cbx_comunidad").data('id'));
    }
  });
});
在您的html中:

<select data-id="$user->comunidad_id"
        class="form-control @error('cbx_comunidad') is-invalid @enderror"
        name="cbx_comunidad"
        id="cbx_comunidad"
        required>
</select>

如果计划将php变量作为JS参数传递,则需要回显它们。 onload=setDefault{{$user->comunidad_id}

您也可以在select上使用data-*属性

Seleccione Comunidad: $'cbx_comunidad'。在“更改”上,functionevent{ $.ajax{ 键入:“GET”, url:'/provincias/'+event.target.value, 成功:功能响应{ let value=$cbx_provincia.attr'data-id'; $cbx_provincia.empty; $cbx_provincia.prependSeleccione provincia; 对于i=0;i