最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - use an anchor to load a page sending post data - Stack Overflow

programmeradmin4浏览0评论

I'm not even sure if this is possible, but I need to send POST data to a page via a user-clicked link. Can this be done?

To be clear, I do not want the data returned to the current page; the target page should load in the browser just as though the user had submitted a form, but I need to send the post data without a form, if possible

I'm not even sure if this is possible, but I need to send POST data to a page via a user-clicked link. Can this be done?

To be clear, I do not want the data returned to the current page; the target page should load in the browser just as though the user had submitted a form, but I need to send the post data without a form, if possible

Share Improve this question edited Sep 15, 2010 at 21:58 Will asked Sep 15, 2010 at 21:49 WillWill 5,6109 gold badges38 silver badges51 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

What do you mean without a form? Can the form be "invisible" to the user? If so, you could do something like:

$("a.post").click(function (e) {
    e.preventDefault();

    $("<form action='"+this.href+"' method='post'></form>").submit();
});

Obviously it could be done many different ways, but you get the idea.

It would be just like a form with the POST parameters intact in the request just in case you use that information at the server when serving up that page.

How about a form with a hidden input? Just create a click event on the anchor tag that submits the form:

<script type="text/javascript">
$(function () {
    $("#postLink").click(function () {
        $("#form").submit();
    });
});
</script>

<a id="postLink" href="javascript:;;">click to post</a>
<form id="form" action="[postTargetUrl]" method="post">
    <input type="hidden" name="postVariable" value="[postValue]" />
</form>

I would just add the data to the url, then the target page can extract it:

Main Page:

<a href="page2.htm?name=Fred">Fred</a>

Target page (page2.htm)

$(document).ready(function(){
 var name = gup("name", window.location.href);
 alert(name);
});

/* Returns URL parameter
 * url: http://www.somesite.?name=hello&id=11111
 * z = gup('name', window.location.href); // z = hello
 * Original code from Netlobo. (http://wwwlobo./url_query_string_javascript.html)
 */
function gup(n,s){
 n = n.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]");
 var p = (new RegExp("[\\?&]"+n+"=([^&#]*)")).exec(s);
 return (p===null) ? "" : p[1];
}
发布评论

评论列表(0)

  1. 暂无评论