开发者

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
        });
   开发者_如何学C });
});

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜