如何通过ajax获取数据,将php变量传递给外部php文件?
问题描述:
I have 2 files, index.php and ajax.php, I am retrieving data from ajax.php to display in index.php via ajax.. I would like to pass the username to ajax.php to use in my sql statement.. How can I achieve this?
index.php -
$profile_user =$_GET['user'];
$(document).ready(function(){
$('.loader').hide();
var load = 0;
var nbr = "<?php echo $nbr;?>";
$(window).scroll (function(){
if($(window).scrollTop() == $(document).height() - $(window).height()){
$('.loader').show();
load++;
if(load * 5 > nbr){
$('.messages').text("No more to see..");
$('.loader').hide();
}else{
$.post("ajax.php", {load:load},function(data){
$(".images").append(data);
$('.loader').hide();
});
}
}
});
});
ajax.php
$profile_user =$_GET['user'];
$sql = "SELECT * FROM images WHERE user = '$profile_user' ORDER BY ID DESC ";
Can I pass the variable in the ajax call?
我有2个文件,index.php和ajax.php,我正在从ajax.php中检索数据以显示在 index.php通过ajax ..我想将用户名传递给ajax.php以在我的sql语句中使用..我怎样才能实现这个目的? p>
index.php - p >
$ profile_user = $ _ GET ['user'];
$(document).ready(function(){
$('。loader')。hide() ;
var load = 0;
var nbr =“&lt;?php echo $ nbr;?&gt;”;
$(window).scroll(function(){
if($(window).scrollTop ()== $(document).height() - $(window).height()){
$('。loader')。show();
load ++;
if(load * 5&gt; nbr){
$('。messages')。text(“No more to see ..”);
$('。loader')。hide();
} else {
$。 post(“ajax.php”,{load:load},function(data){
$(“。images”)。append(data);
$('。loader')。hide();
});
}
}
});
});
code> pre>
ajax.php p>
$ profile_user = $ _ GET ['user'];
$ sql =“SELECT * FROM images WHERE user ='$ profile_user'ORDER BY ID DESC”;
code> pre>
Can 我在ajax调用中传递变量? p>
div>
答
Add the PHP variable in the AJAX call
$.post("ajax.php", {
load: load,
user: '<?php echo $profile_user; ?>'
},function(data){
And change $_GET
by $_POST
in your ajax.php file, like this
$profile_user = $_POST['user'];
答
You need to POST that data:
$.post('ajax.php', {load:load, user: '"<?php echo $_GET['user'];?>"'},function(data){
$('.images').append(data);
$('.loader').hide();
});
答
You can change
$.post("ajax.php", {load:load},function(data){
$(".images").append(data);
$('.loader').hide();
});
to
$.post("ajax.php", {load:load, user:user},function(data){
$(".images").append(data);
$('.loader').hide();
});
And in ajax.php after getting mysql result just encode the array in json format and echo it.
$data = mysql_query($sql);
echo json_encode($data);exit;