2

我想知道哪个是映射<a href=...></a>执行 HTTP GET 的超链接以执行 HTTP POST 的最佳方式(我想避免在 URL 中传递所有变量)?比如hrefs下面的2。此外,我还想摆脱submit按钮并使用常规<a href=...></a>超链接。有什么建议么?

<form action="test.php?action=update" method="post" id="cart">
  <table>
    <tr>
      <td>
        <a href="test.php?action=delete&id=<?php echo $id ?>" class="r">
          remove
        </a>
      </td>
      <td>
        <a href="test.php?action=add&id=<?php echo $id ?>" class="r">add</a>
      </td>
    </tr>
    <tr>
     ...
    </tr>
  </table>
  <div> <button type="submit">Update</button> </div>
</form>
4

3 回答 3

2

我建议使用jQuery.post单击。单击链接后,通过类似这样的方式提交数据

$('.r').on('click', function() {
        $.post('test.php', {key:'value', key2:'value2'}, function(data) {
          //error check here
        });
    return false;
});
于 2012-12-11T08:45:05.963 回答
0

As far as i know you can't perform any POST requests with links. You can make your GET requests with links and php as a fallback for users with javascript disabled and for those who have javascript enabled cancel default behavior for links with javascript and make with ajax your POST request with help of AJAX.

for example:

<a class="submit" href="hallo.html?hello=world&test=yes">Test</a>

and js(i used jquery) would be:

$('.submit').click(function(){
    var urlPairs = this.href.split('?')[1].split('&'),
        total = urlPairs.length,
        current = [],
        data = {};

    for(;total;) {
        current = urlPairs[--total].split('=');
        data[current[0]] = current[1];
    }

    $.post('test.php', data);

    return false;
});

​</p>

you could also write your POST function other for more info check jQuery post function doc

P.S. I wounder, if you are using FORM any way why wouldn't you use submit button, is it because of CSS styling? You could style it the same way like any other element(with some tweaks in some browsers).

于 2012-12-11T10:18:57.323 回答
0

您可以将输入标签隐藏在表单中,以将它们作为 POST 提交。

<td><a href="test.php?action=delete&id=<?php echo $id;?>" class="r">remove</a></td>
<td><a href="test.php?action=add&id=<?php echo $id;?>" class="r">add</a></td>

使用两种形式重写上述内容,有<input type="hidden" name="id /> 和按钮<input type="button" name="delete" /> 等。

如果您在操作脚本中运行 print_r($_POST)。您将获得按钮列表和隐藏字段的值。现在,您可以为要运行的操作编写条件。我这里没有写完整的代码,只是传递一下思路。

编辑:见下面的例子。

     <form  method="post" id="cart">
        <table>
                <input type="hidden" name="id" value='some value' />
                <input type="submit" name="action" value="delete" />
                <input type="submit" name="action" value="add" />
            </tr>
            <tr>
                ...
            </tr>
        </table>
        <div><button type="submit">Update</button></div>
     </form>


    <?php print_r($_POST); ?>
于 2012-12-11T08:39:29.323 回答