简体   繁体   English

使用jQuery .get在URL中显示参数

[英]Using jQuery .get to show parameters in URL

When using a GET request on a form in regular HTML we get the variables within the URL. 在常规HTML表单上使用GET请求时,我们会在URL中获取变量。 Is there a Jquery way to sent variables like this by clicking a button? 是否存在通过单击按钮发送像这样的变量的Jquery方法? I have been looking into Jquery .get but i can't get my parameters to show up in the URL. 我一直在研究Jquery .get,但是我无法获取显示在URL中的参数。

Following does not load the page and add to URL, it just runs the code with specified parameters. 以下代码不会加载页面并添加到URL,它只会运行带有指定参数的代码。

$.get( "home.php", { name: "menyo" } );

So i am looking for a way to do this in a clean Jquery way. 因此,我正在寻找一种以干净的Jquery方式执行此操作的方法。 It is because i have many buttons that do various Jquery things and i do not want to create a form for each one with their own get request while i automated buttons with button classes using custom attributes in the HTML. 这是因为我有许多执行各种Jquery事情的按钮,并且我不想使用自己的get请求为每个按钮创建一个表单,而我却使用HTML中的自定义属性来自动处理具有按钮类的按钮。

What you have to do is to create a method that will find all inputs in given form and prepare a JSON Object with key value pair. 您要做的是创建一个方法,该方法将查找给定格式的所有输入,并准备一个具有键值对的JSON对象。

something like that 这样的东西

function getFormJson(formId) {
    var jsonObject = {};
    $("form#" + formId).find("input").each(function (i, item) {
        jsonObject[item.attr("name")] = item.val();
    });
    return jsonObject
}

To move the location of the window I believe you can do something like this: 我相信要移动窗口的位置,您可以执行以下操作:

window.location.href = "home.php?name=menyo";

Otherwise I'd look into checking out pushState, which will change the URL of a page without actually taking you there. 否则,我将考虑签入pushState,这将更改页面的URL,而实际上并没有带您到那里。

pushState docs: pushState文档:

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState().C2.A0method https://developer.mozilla.org/zh-CN/docs/Web/Guide/API/DOM/Manipulating_the_browser_history#The_pushState().C2.A0方法

Otherwise, you can use classic AJAX 否则,您可以使用经典的AJAX

$("#button").click(function(){
    $.ajax({
        type: "GET",
        url: "where/you/need/the/variables.php",
        data: { 
            "name" : "menyo"
        },
        success: function(data){
            // data is the returned output of the page
        }
    });
})

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

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