JQuery - 将 POST 变量添加到 href 链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7022167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:43:06  来源:igfitidea点击:

JQuery - Add POST variables to a href link

jquery

提问by elaxsj

In a table I have links like this: test.php?id=1

在表格中,我有这样的链接: test.php?id=1

I want to pass prev_idand next_idto test.php as well. (Purpose of these variables is create next/prev buttons; the list can be sorted by the user so no easy way to find out inside test.php.)

我也想通过prev_idnext_idtest.php。(这些变量的目的是创建下一个/上一个按钮;列表可以由用户排序,因此在 test.php 中很难找到。)

However, I do not want prev_idand next_idto be visible in the URL for the user. Can I format the href like this:

但是,我不希望prev_id并且next_id在用户的 URL 中可见。我可以像这样格式化 href 吗:

<a href="test.php?id=1" prev_id="5" next_id="45">

and use JQuery to "hiHyman" the link, keeping id as GET in the URL, but sending prev_idand next_idto test.php as POST?

并使用jQuery“劫持”的链接,保持ID作为GET的URL,但发送prev_idnext_id对test.php的作为POST?

回答by Erik Márf?ldi

Maybe this is your code:

也许这是你的代码:

 <a id="link" href="test.php?id=1" prev_id="5" next_id="45">

and the jquery code

和 jquery 代码

$("a#link").click(function(){

    $.post("test.php",
       {
         prev_id: $(this).attr("prev_id"),
         next_id: $(this).attr("next_id")
       },
       function(data) {
         alert("Data Loaded: " + data);
       }
    );

    return false;
});

回答by sanepete

The easiest way I've found to do this kind of thing is to dynamically add a form to your page then submit it:

我发现做这种事情的最简单的方法是动态地向你的页面添加一个表单,然后提交它:

$('body').append('<form id="myawesomeform"></form>');
$('#myawesomeform').attr('action','test.php?id=1');
$('#myawesomeform').attr('method','post"');
$('#myawesomeform').append('<input type="hidden" name="prev_id" id="prev_id" value="5">');
$('#myawesomeform').append('<input type="hidden" name="next_id" id="next_id" value="45">')
$('#myawesomeform').submit();

回答by Jayantha Lal Sirisena

you can use jquery post

你可以使用 jquery 帖子

call a function to post your data by onClick event,

通过 onClick 事件调用一个函数来发布您的数据,

 <a onClick="postdata()" prev_id="5" next_id="45">

and the jquery code

和 jquery 代码

function postdata(){
    $.post("test.php", { id: "1", next_id: "2" },
       function(data) {
         alert("Data Loaded: " + data);
       });
}