将jQuery Ajax代码片段转换为HTMX或获取选择器值管理。

huangapple go评论43阅读模式
英文:

Translate jquery ajax code snippet into HTMX or manage to fetch selector value

问题

我使用 htmx 构建了 3 个相互依赖的选择列表(国家、地区、城镇),并成功获取了最后一个部分的选定城镇,如下所示:

<select id="localidades" class="form-control-sm custom-select"
        name="town"
        hx-get="{% url 'query_for_properties' %}"
        hx-trigger="change"
        hx-target="#response"
        required>
    <option value="">选择市区</option>
    {% for z in lista_localidades %}
    <option value="{{z}}">{{z}}</option>
    {% endfor %}
</select>

在这里,我成功获取了城镇值(请注意,我是从上面的代码片段中调用此函数):

def query_for_properties(request):
    town = request.GET.get('town')
    # 其他操作

然而,接下来的代码需要将值发送到不同的目标,并为每个目标提供不同的值,例如汽车数量、自行车数量等。这就是我遇到困难的地方。htmx 文档通常只针对非常简单的情况,但如果你需要其他东西,可能会感到困扰。我不知道如何将不同的值分配给不同的目标。

所以,我尝试了使用 jQuery 的 Ajax,对于每个选择器构建调用很容易。然而,因为我使用 htmx 构建了相互依赖的选择列表,Ajax 查询没有获取到值。以下是代码示例:

<script>
$(document).ready(function(){
    $("#localidades").on({
        change: function(){
            var ciudad = $('#localidades').val();
            alert(ciudad);
            $.ajax({
                url: 'testing',
                type: "GET",
                'success': function(data) {
                    $('#store').html(data);
                }
            }); // 关闭 Ajax 函数
            $("#house").css("background-color", "lightgray");

            $.ajax({
                url: 'housecount',
                type: "GET",
                'success': function(data) {
                    $('#house').html(data);
                }
            }); // 关闭 Ajax 函数

            $("#store").css("background-color", "lightblue")

            $("#response").css("background-color", "yellow");
        },
    });
});
</script>

当我尝试警告该值时,我得到了空值。

然而,因为第一个选择列表是这样构建的:

def index_country(request):
    country = Address.objects.distinct('country')
    print(country)
    return render(request, 'index.html',{'country':country})
<select id="paises" class="form-control-sm custom-select" required
        name="country"
        hx-get="{% url 'index_regiones' %}"
        hx-trigger="change"
        hx-target="#regiones">
    <option value="">选择国家</option>
    {% for x in country %}
        <option value="{{x.country}}">{{x.country}}</option>
    {% endfor %}
</select>

对于这个选择列表,它可以正常工作:

var pais = $('#paises').val();
alert(pais);

但是对于 "localidades" 则不行,正如我在开始时提到和展示的那样。

我首先尝试使用 htmx 获取值,我成功了,但随后不知道如何将结果发送到不同的目标,所以变得过于复杂。

使用 Ajax 正好相反,我可以将不同的调用发送到不同的选择器,但无法获取第一个初始值。

英文:

I built a 3 interdependent select lists using htmx, (country region town) and I managed to fetch the selected town as I have this on the last part

&lt;select id=&quot;localidades&quot; class=&quot;form-control-sm custom-select &quot;
    name=&quot;town&quot;
    hx-get=&quot;{% url &#39;query_for_properties&#39; %}&quot;
    hx-trigger=&quot;change&quot;
    hx-target=&quot;#response&quot;
    required&gt;
 &lt;option value=&quot;&quot;&gt;Select municipality&lt;/option&gt;
 {% for z in lista_localidades %}
 &lt;option value=&quot;{{z}}&quot;&gt;{{z}}&lt;/option&gt;

{% endfor %}
&lt;/select&gt;`

Here I fetch it alright (notice that I am calling this function from the above snippet)

def query_for_properties(request):
  town = request.GET.get(&#39;town&#39;)
  etc

as I need that town value for the next code. However, this next code needs to send the values to different targets and for each target a different value, like, number of cars, number of bikes etc to different selectors.And that is where I get stuck.The htmx docs, as usual everywhere, are only for the very simple scenarios, but if you need something else, you are a goner, stranded. I have no idea how to deal out different values to different targets.

So, I tried ajax, and with jquery it was easy to build calls for every selector. However, because I built the interdependent select lists with htmx,ajax query doesn't get the value. Here it goes

&lt;script&gt;

    $(document).ready(function(){
    $(&quot;#localidades&quot;).on({
    change: function(){
    var ciudad = $(&#39;#localidades&#39;).val();
    alert(ciudad);
     $.ajax({
              url: &#39;testing&#39;,
              type: &quot;GET&quot;,
              &#39;success&#39;: function(data) {
              $(&#39;#store&#39;).html(data);
              }
      }); // close ajax function
      $(&quot;#house&quot;).css(&quot;background-color&quot;, &quot;lightgray&quot;);

       $.ajax({
              url: &#39;housecount&#39;,
              type: &quot;GET&quot;,
              &#39;success&#39;: function(data) {
              $(&#39;#house&#39;).html(data);
              }
      }); // close ajax function

      $(&quot;#store&quot;).css(&quot;background-color&quot;, &quot;lightblue&quot;)

      $(&quot;#response&quot;).css(&quot;background-color&quot;, &quot;yellow&quot;);
    },

  });
});
&lt;/script&gt;`

when I try to alert the value, I get nothing, empty.

however, because the first select list was built like this:

def index_country(request):
  country = Address.objects.distinct(&#39;country&#39;)
  print(country)
  return render(request, &#39;index.html&#39;,{&#39;country&#39;:country})


&lt;select id=&quot;paises&quot; class=&quot;form-control-sm custom-select&quot; required
                            name=&quot;country&quot;
                            hx-get=&quot;{% url &#39;index_regiones&#39; %}&quot;
                            hx-trigger=&quot;change&quot;
                            hx-target=&quot;#regiones&quot;&gt;
                            &lt;option value=&quot;&quot;&gt;Select country&lt;/option&gt;
                            {% for x in country %}
                                &lt;option value=&quot;{{x.country}}&quot;&gt;{{x.country}}&lt;/option&gt;
                            {% endfor %}
&lt;/select&gt;

it gets it alright,
var pais = $('#paises').val();
alert(pais);

but it doesn't get it for localidades as I mentioned and showed at the beginning.

I tried first htmx to fetch the value and I did, but then I don't know how to send the results to different targets, so too complicated

With ajax is the opposite, I can deal out different calls to different selectors but I can't fetch the first initial value.

答案1

得分: 1

我的诊断不正确,因此我在问题中也没有提到这一点。

这些有关国家、地区和城镇的代码片段实际上是注入到主页面中的。但事实证明,选择列表的id与它自己注入的div的id相同。因此,选择器值混乱,不知道要附加到哪个性别身份。我告诉它不能有两种性别的实体,所以我更改了名称,问题就解决了。

英文:

My diagnosis was not correct and therefore I also failed to mention the point in my question.

Those code snippets for country, region, town were actually injected into the main page. But it turned out that the id of the select list was the same of the div it was injecting itself to. Therefore, the selector value was freaking out not knowing which gender identity to attach to. I instructed it that there could not be an entity with two genders so I changed the name and the problem was solved.

huangapple
  • 本文由 发表于 2023年6月6日 01:34:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76408787.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定