简体   繁体   中英

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. 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. 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. How can I do this?

What you have works: jQuery's AJAX converts { name: 'John' } to submit.php?name=John .

And you'd access it in your PHP script like this:

<?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; 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 ...

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.

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