我点击多个按钮后,如何获取所点击按钮的数组索引?

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

How can I get the array index of a button I clicked out of multiple buttons

问题

我有一个购物车表单,通过$_SESSION迭代列出每个存储的项目的详细信息。该表单包括相同的多个表单控件,包括用于取消的<button>元素。

我面临的问题是,我无法让PHP识别点击了哪个取消<button>,因此无法指定要从表单中删除的项目。

表单控件的代码如下:

    ......

    if(isset($_SESSION[$i]['stocks']) && $_SESSION[$i]['stocks'] !== ''):
    echo '<dl><dt>Quantity</dt><dd><input name="stock[]" type="text" value="'.$_SESSION[$i]['stocks'].'"></dd></dl>';
    endif;
    echo '<button name="cancel[]">Cancel</button>';
    ......

取消按钮具有数组格式的name属性,同时运行var_dump会返回$_SESSION[]的所有内容。

请帮助我找到识别点击了哪个取消按钮的任何方法。

谢谢阅读。

英文:

I have a form for a shopping cart that lists the details of each stored item by iteration using $_SESSION. This form consists of same multiple form controls including &lt;button&gt; elements for cancellation.

The problem I'm faced with is I cannot get PHP to identify which cancellation &lt;button&gt; was clicked, so I'm unable to specify the item to delete from the form.

The code of the form controls goes:

......

if(isset($_SESSION[$i][&#39;stocks&#39;]) &amp;&amp; $_SESSION[$i][&#39;stocks&#39;] !== &#39;&#39;):
echo &#39;&lt;dl&gt;&lt;dt&gt;Quantity&lt;/dt&gt;&lt;dd&gt;&lt;input name=&quot;stock[]&quot; type=&quot;text&quot; value=&quot;&#39;.$_SESSION[$i][&#39;stocks&#39;].&#39;&quot;&gt;&lt;/dd&gt;&lt;/dl&gt;&#39;;
endif;
echo &#39;&lt;button name=&quot;cancel[]&quot;&gt;Cancel&lt;/button&gt;&#39;;
......

The cancel button has an name attribute in array format and also running var_dump returns all of the content of $_SESSION[].

Please help me find any ways to identify which cancel button was clicked.

Thanks for reading this.

答案1

得分: 0

每个HTML按钮元素都可以有一个value属性。只需用您需要的标识符填充它以识别您的取消按钮。

当提交表单时,您可以在您的php脚本中使用 `$_POST['cancel']` 来访问标识符。

只有当按钮用于提交表单时,按钮及其值才会被提交。您必须使用type属性来提交表单。

在使用AJAX时(千万不要使用jQuery!),在按钮上设置事件侦听器时无需使用type属性。只需读取值并将其用作请求的查询参数。

此示例设置了一个事件侦听器,监听点击事件,并异步向`cancel.php`发送带有查询参数的请求,例如 `item=1`。值是从每次点击的按钮的value属性动态确定的,并在PHP脚本中使用 `$_GET['item']` 可供您使用。

所示示例并不好,因为它为每个按钮设置了一个事件侦听器。这可能会导致HTML页面的性能问题,具体取决于按钮的数量。最好的做法是在父表单元素上设置一个单独的事件侦听器,然后用它来确定相应的按钮。所示示例仅供参考。

有关使用JavaScript fetch API 的详细信息:https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
英文:

Every HTML button element can have a value attribute. Just fill it with the identifier you need to identify your cancel button.

&lt;button name=&quot;cancel&quot; value=&quot;&lt;?= htmlspecialchars($i) ?&gt;&quot; type=&quot;submit&quot;&gt;
    Cancel
&lt;/button&gt;

When submitting the form you can access the identifier with $_POST[&#39;cancel&#39;] in your php script.

The button and its value is only submitted if the button was used to submit the form. You have to use the type attribute to submit the form.

When using AJAX (for god 's sake don 't use jQuery!) you don 't have to use the type attribute when setting an event listener on the button. Just read out the value and use it as query argument for your request.

&lt;button name=&quot;cancel&quot; value=&quot;&lt;?= htmlspecialchars($i) ?&gt;&quot;&gt;
    Cancel
&lt;/button&gt;
&lt;script&gt;
let buttons = document.querySelectorAll(&#39;button[name=&quot;cancel&quot;]&#39;);
buttons.forEach(button =&gt; {
    button.addEventListener(&#39;click&#39;, async (event) =&gt; {
        event.preventDefault();
        let value = event.currentTarget.value;
        let response = await fetch(&#39;cancel.php?item=&#39; + value);
        ...
    });
});
&lt;/script&gt;

The example sets an event listener that listens on a click event and fires an async request to cancel.php with the query argument, e.g. &#236;tem=1. The value is determined dynamically from the value attribute of the button with each click and is available to you in the PHP script with $_GET[&#39;item&#39;].

The example shown is not good because it sets an event listener for each button. This can lead to performance problems of the HTML page depending on the number of buttons. It would be better if a single event listener is set on the parent form element, which is then used to determine the respective buttons. The example shown is only intended as an illustration.

For details using the JavaScript fetch API: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

答案2

得分: 0

以下是您要翻译的部分:

首先,您必须为每一行分配一个唯一的ID或值。下面的示例可能会有所帮助。

我在这里所做的是,我只是向button标签添加了一个名为data-target的新自定义属性。除此之外,我还添加了一个自定义类actionBtn来在JS中识别所有这些按钮。

......

if(isset($_SESSION[$i]['stocks']) && $_SESSION[$i]['stocks'] !== ''):
echo '<dl><dt>Quantity</dt><dd><input name="stock[]" type="text" value="'.$_SESSION[$i]['stocks'].'"></dd></dl>';
endif;

// 你可以更改数组元素,使用每行的唯一ID或唯一值,而不是`$_SESSION[$i]['stocks']`
echo '<button class="actionBtn" name="cancel[]" data-target="'.$_SESSION[$i]['stocks'].'">Cancel</button>';
......

在此之后,我创建了一个JS事件,当这些按钮被点击时触发JS函数。我假设您的项目中使用了jQuery。

<script>
$(function(){
     $('.actionBtn').on('click',function(event){
          // 取消按钮点击时的所有默认操作。
          event.preventDefault();
         
          // 为了让你理解,我们创建了一个变量,用于存储需要从`$_SESSION`中移除的值。
          var target_to_remove = $(this).attr('data-target');

          // 现在我通过AJAX调用将值发送到服务器。
          $.post('<some_destination_url>.php',{target : target_to_remove},function(response){
             /* ... 从服务器接收响应后在此执行必要的操作 ... */
             if($.trim(response) == 'success')
             {
                 alert('success');
             } else {
                 alert('failed');
             }
          });
     });
});
</script>

现在JS部分已经完成,我们必须在PHP脚本中捕获$_POST数据。

文件: `<some_destination_url>.php

  if(isset($_POST['target']))
  {
      for($i=0;$i<count($_SESSION);$i++)
      {
          if($_SESSION[$i]['stocks'] == $_POST['target'])
          {
               /* 如果你想要删除整个父数组,请使用下面的方法 */
               //unset($_SESSION[$i]);

               /* 如果你只想删除第三级数组元素,请使用下面的方法 */
               //unset($_SESSION[$i]['stocks']);

               // 最后向JS回显一些内容,以便它知道任务是否成功。
               echo 'success';
          }

      }
      // 如果没有找到元素,则输出失败信息。
      echo 'item not found';
  }
  else 
  {
     // 如果`$_POST`未设置,则输出一些内容。
     echo 'Invalid attempt to remove array element.';
  }

希望这可以帮助您理解并使用这段代码。

英文:

First you have to identify each row with some unique ID/value. Below shown example may help you.

What I have done here is, I have just added a new custom attribute to button tag called data-target. Along with this, I have added a custom class actionBtn to identify all such buttons in JS.

......

if(isset($_SESSION[$i][&#39;stocks&#39;]) &amp;&amp; $_SESSION[$i][&#39;stocks&#39;] !== &#39;&#39;):
echo &#39;&lt;dl&gt;&lt;dt&gt;Quantity&lt;/dt&gt;&lt;dd&gt;&lt;input name=&quot;stock[]&quot; type=&quot;text&quot; value=&quot;&#39;.$_SESSION[$i][&#39;stocks&#39;].&#39;&quot;&gt;&lt;/dd&gt;&lt;/dl&gt;&#39;;
endif;

// you can change the array element with unique ID or unique value for each row instead of `$_SESSION[$i][&#39;stocks&#39;]`
echo &#39;&lt;button class=&quot;actionBtn&quot; name=&quot;cancel[]&quot; data-target=&quot;&#39;.$_SESSION[$i][&#39;stocks&#39;].&#39;&quot;&gt;Cancel&lt;/button&gt;&#39;;
......

After this, I have created a JS event which triggers a JS function when these buttons clicked. I am assuming you are using jQuery in your project.

&lt;script&gt;
$(function(){
     $(&#39;.actionBtn&#39;).on(&#39;click&#39;,function(event){
          // cancel all default actions when button clicked.
          event.preventDefault();
         
          // to make you understand, we are creating a variable which stores the values that needs to be removed from `$_SESSION`
          var target_to_remove = $(this).attr(&#39;data-target&#39;);

          // Now I am sending the value to server via AJAX call.
          $.post(&#39;&lt;some_destination_url&gt;.php&#39;,{target : target_to_remove},function(response){
             /* ... Do necessary action here after you receive response from server ... */
             if($.trim(response) == &#39;success&#39;)
             {
                 alert(&#39;success&#39;);
             } else {
                 alert(&#39;failed&#39;);
             }
          });
     });
});
&lt;/script&gt;

Now as the JS part is done, We have to capture the $_POST data in PHP script.

File: <some_destination_url>.php

  if(isset($_POST[&#39;target&#39;]))
  {
      for($i=0;$i&lt;count($_SESSION);$i++)
      {
          if($_SESSION[$i][&#39;stocks&#39;] == $_POST[&#39;target&#39;])
          {
               /* if you want to remove whole parent array then use below */
               //unset($_SESSION[$i]);

               /* if you want to remove 3rd level array element only, then use below */
               //unset($_SESSION[$i][&#39;stocks&#39;]);

               // finally echo something back to JS so that it knows task was successfull or not.
               echo &#39;success&#39;;
          }

      }
      // echo failure if no elements found.
      echo &#39;item not found&#39;;
  }
  else 
  {
     // echo something if `$_POST` is not set.
     echo &#39;Invalid attempt to remove array element.&#39;;
  }

huangapple
  • 本文由 发表于 2023年5月10日 13:40:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/76215211.html
匿名

发表评论

匿名网友

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

确定