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

javascript - Submit a form without query string - Stack Overflow

programmeradmin1浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论