I have a form rendered in Ruby On Rails, looks like this:
<%= form_tag myaction_path(item_id: item.id),
{ class: 'myaction',
id: "myaction_#{item.id}",
method: :get,
remote: true } do %>
and I process the data in JS:
$(document).ready(function () {
$(".myaction").submit(function(event){
event.stopPropagation();
event.stopImmediatePropagation();
event.preventDefault();
console.log($(this).attr("action"));
...
console.log($(this).attr("action"));
returns /app/myaction?item_id=5528
.
I need the item_id
as a key to access other items in the form. Is there any elegant way to fetch it from $(this).attr("action")
or do I need to manually parse the string ( /app/myaction?item_id=5528
)?
There is no way to get the query string from the form action. You have to parse it manually.
let str = $(this).attr("action");
function parseQueryString(str) {
let query = str.split("?");
if (query.length > 1) {
let item = query[1].split("=");
return item[1] ? item[1] : "";
}
}
let result = parseQueryString(str);
console.log(result);
You can store the item_id in the hidden input field. Or else if you want to parse the item_id or any other field from the action then you can use below js function:
function parseURL(url) { var searchObject = {} let queries = new URL(url).search.replace(/^\\?/, '').split('&'); for( i = 0; i < queries.length; i++ ) { split = queries[i].split('='); searchObject[split[0]] = split[1]; } return searchObject; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.