简体   繁体   English

如何使用JQuery / AJAX向URL添加参数

[英]How to add parameters to the URL with JQuery/AJAX

When using the get method on an HTML form the submitted data shows up in the URL. 在HTML表单上使用get方法时,提交的数据将显示在URL中。 This page shows what I mean. 此页面显示了我的意思。 I have been trying to get this to work with JQuery and AJAX using the get method but the data is not showing up in the URL for some reason. 我一直在尝试使用get方法将其与JQuery和AJAX结合使用,但是由于某种原因数据未显示在URL中。 Does anyone know why? 有人知道为什么吗? Here is my code: 这是我的代码:

$(function() {
    $('#mylink').click(function () {    
        $.get("submit.php", { name: 'John' }, function(data) {
            // blah blah blah
        });
    });
});

I want the end of the URL to be appended with ?name=John and be able to access it with the $_GET variable. 我希望将URL的末尾附加?name = John并能够使用$ _GET变量进行访问。 How can I do this? 我怎样才能做到这一点?

What you have works: jQuery's AJAX converts { name: 'John' } to submit.php?name=John . 您的工作原理:jQuery的AJAX将{ name: 'John' }submit.php?name=John

And you'd access it in your PHP script like this: 您可以像这样在您的PHP脚本中访问它:

<?php
echo $_GET["name"]; //ECHOs out "John"
?>

BTW don't forget to prevent the link from changing the page - 顺便说一句,别忘了阻止链接更改页面-

$('#mylink').click(function() {    
    $.get("submit.php", { name: 'John' }, function(data) {
        // blah blah blah
    });
    return false; //Prevents the default behavior of the link
});

Looks like you're missing return false; 好像您缺少return false; in the click handler. 在点击处理程序中。 Probably why you're not seeing what you expect. 可能是为什么您没有看到期望的结果。

Eg 例如

$(function() {
    $('#mylink').click(function () {    
        $.get("submit.php", { name: 'John' }, function(data) {
            // blah blah blah
        });
        return false;
    });
});

Why not just append it to the link? 为什么不将其附加到链接?

$.get("submit.php?name=" + username), function(data){ ... });

BTW...please heed all the normal warnings out there about server side sanitation of your input url. 顺便说一句...请注意有关输入网址的服务器端环境卫生的所有常规警告。 No one wants to meet Little Bobby Tables ... 没有人想见小鲍比桌子 ...

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

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