javascript - Submit a form without query string - Stack Overflow

I'm on a page likethat has a form <form id="formId" method="POST">. Wh

I'm on a page like that has a form <form id="formId" method="POST">.

What's the best way to submit the form to without the query string?

I'm currently trying:

$('#formId').submit(function(e){
    e.preventDefault();
    var url = window.location.href; 
    if (url.indexOf("?") != -1){
        $('#formId').attr('action', url.split("?")[0]);
    }
    $('#formId').submit();
});

but it doesn't seem to be working.

I prefer a javascript/jQuery solution as this pattern is mon through the site

I'm on a page like http://example.?query=value that has a form <form id="formId" method="POST">.

What's the best way to submit the form to http://example. without the query string?

I'm currently trying:

$('#formId').submit(function(e){
    e.preventDefault();
    var url = window.location.href; 
    if (url.indexOf("?") != -1){
        $('#formId').attr('action', url.split("?")[0]);
    }
    $('#formId').submit();
});

but it doesn't seem to be working.

I prefer a javascript/jQuery solution as this pattern is mon through the site

Share Improve this question asked Aug 29, 2016 at 23:00 MilkMilk 2,6536 gold badges37 silver badges57 bronze badges 3
  • Umm what do you want? – Adam Buchanan Smith Commented Aug 29, 2016 at 23:02
  • 2 Why don't you just set the action attribute in the HTML? In theory, it's a required attribute on <form> elements – Phil Commented Aug 29, 2016 at 23:14
  • @Phil because that would require knowledge of the page url during page initiation, which I don't have due to my templating strategy. Thus why I'm asking for a Javascript/jQuery solution, which would be easy to include on each page. – Milk Commented Aug 30, 2016 at 0:04
Add a ment  | 

2 Answers 2

Reset to default 2

Instead of attempting to change the action on submit, how about just looking for forms without action attributes and setting them appropriately, for example

jQuery(function($) {
    $('form:not([action])').attr('action', location.pathname);
});

For anyone else looking here, a quick and dirty solution is to set the form action attribute to "?". eg:

<form id="formId" method="POST" action="?">

This will post the request to the current url with the query string just being a single "?"

Though as this does not use javascript, it might not be the answer OP is after.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745479021a4629479.html

相关推荐

  • javascript - Submit a form without query string - Stack Overflow

    I'm on a page likethat has a form <form id="formId" method="POST">. Wh

    3小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信