简体   繁体   English

JavaScript/jQuery:如何从 .attr("action") 获取参数及其值?

[英]JavaScript/jQuery: how to get parameters with their values from .attr("action")?

I have a form rendered in Ruby On Rails, looks like this:我有一个在 Ruby On Rails 中呈现的表单,如下所示:

<%= 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:我在 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 .返回/app/myaction?item_id=5528

I need the item_id as a key to access other items in the form.我需要item_id作为访问表单中其他项目的键。 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 )?有什么优雅的方法可以从$(this).attr("action")获取它,还是我需要手动解析字符串( /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.您可以将 item_id 存储在隐藏的输入字段中。 Or else if you want to parse the item_id or any other field from the action then you can use below js function:否则,如果您想从操作中解析 item_id 或任何其他字段,则可以使用以下 js 函数:

 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; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM