我正在尝试使用JavaScript将多个变量传递到php页面。目前,JavaScript代码将变量“page”发布到fetch_pages.php。我想发布另一个变量'currentpage'。 javaScript代码如下:
<script type="text/javascript">
$(document).ready(function() {
var track_click = 0; //track user click on "load more" button, righ now it is 0 click
var total_pages = <? php echo $total_pages; ?> ;
$('#results').load("/include/fetch_pages.php", {
'page': track_click
}, function() {
track_click++;
}); //initial data to load
$(".load_more").click(function(e) { //user clicks on button
$(this).hide(); //hide load more button on click
$('.animation_image').show(); //show loading image
if (track_click <= total_pages) //make sure user clicks are still less than total pages
{
//post page number and load returned data into result element
$.post('/include/fetch_pages.php', {
'page': track_click
}, function(data) {
$(".load_more").show(); //bring back load more button
$("#results").append(data); //append data received from server
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
track_click++; //user click increment on load button
}).fail(function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //alert any HTTP error
$(".load_more").show(); //bring back load more button
$('.animation_image').hide(); //hide loading image once data is received
});
if (track_click >= total_pages - 1) {
//reached end of the page yet? disable load button
$(".load_more").attr("disabled", "disabled");
}
}
});
});
我假设我需要在JavaScript代码中添加另一个变量,如:
var currentpage = 'index.php'
然后使用'page'变量发布它,但我是Javascript的新手,我不确定该怎么做。
fetch_pages.php目前显示:
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
我还假设我必须添加变量,如:
$currentpage = $_POST["currentpage "];
任何帮助将不胜感激。感谢。
答案 0 :(得分:2)
在jQuery中,您可以像这样在POST中添加多个值:
$.post('/include/fetch_pages.php',{'page': track_click, 'currentpage' : 'foo'}, function(data) {
#do stuff
}
在您的情况下,您希望传递当前页面。最常见的方法是通过window.location.pathname
。如果您在www.example.com/foo/bar.php
,那么window.location.pathname
将等于foo/bar.php
,我认为这是您想要的。
因此,要完全回答您的问题,您需要这样的代码:
$.post('/include/fetch_pages.php',{'page': track_click, 'currentpage' : window.location.pathname}, function(data) { /* ... */ }
或者,如果您只想要当前文件的名称(例如bar.php
)而没有前面的目录,则可以这样做:
$.post('/include/fetch_pages.php',{'page': track_click, 'currentpage' : window.location.pathname.split( '/' ).slice(-1)[0]}, function(data) { /* ... */ }
然后在您的PHP文件中,您可以非常简单地访问它:
$curr_page = $_POST['currentpage'];
答案 1 :(得分:1)
更改
{'page':track_click}
到
{'page':track_click,'anotherVar':'whatever'}