retrieving data from db based on php's $_GET var with jquery/ajax?
Disclaimer
I have searched for duplicates, but I can't seem to find them. I am surprised because this seems to be a big issue. I most likely am missing something big though.
Problem/Question
I am having the userid
passed into through the url via php
, myOtherScript.php?userid=1
. How can I get that variable to be passed via ajax
so that I may query the database with that userid
, echo it out and return it to the page?
This is in global.js
file
jQuery
$.ajax({
url: "myScript.php",
data: "userid=" - This is what I need: $_GET['userid'] - ,
success: function( data ) {
$('#myDiv').html( data );
}
});
Solution
WIth the help of bstakes and this answer, I was able to figure it out with this function: (top answer)
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex开发者_Python百科 = new RegExp(regexS);
var results = regex.exec(window.location.href);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Thanks for the answers guys!
$.ajax({
url: "myScript.php",
data: "userid=<?php echo intval($_GET['userid']); ?>",
success: function( data ) {
$('#myDiv').html( data );
}
});
You could also try using the search attribute of the window.location object.
If the url is http://www.mysite.com/display.php?userid=7 window.location.search will return "?userid=7". You will obviously need to remove the leading "?", but be aware that if there are additional GET paramaters, separated with ampersand '&', those will be included as well.
So, with a bit of additional Javascript, you can split on the '&', which gets you an array of "key=val", then you can spilt on the equal sign and create an object with {key : val}. Then you could use that object to access the query string params.
var qs = window.location.search.substring(1),
pieces = qs.split('&'),
i,
qsObj {},
tmp;
for ( var i in pieces ) {
tmp = pieces[i].split('=');
qsObj[tmp[0]] = tmp[1];
}
See https://developer.mozilla.org/En/Window.location for additional information on the window.location.
If you want to keep the JS seperate, put it in a function that accepts the user id...
function do_something(user_id) {
$.ajax({
url: "myScript.php",
data: "userid=" + user_id,
success: function( data ) {
$('#myDiv').html( data );
}
});
}
Then just call do_something($_GET['user_id']);
You might have to move the script inline on the PHP file then you echo out the $_GET['userid'] in the data area of your ajax call.
just found this: how to get GET and POST variables with JQuery?
精彩评论