将PHP变量传递给Ajax函数将变量JS转换为PHP

时间:2016-02-13 16:53:19

标签: javascript php jquery ajax

我在理解将信息从PHP传递到JS并返回的逻辑时遇到了实际问题。我一直在努力工作,如果有人能告诉我如何将两个变量传递给ajax函数,我将非常感激。

$ assetPath和$计入下面评论的行。我已经尝试通过添加php来包含它们但是在DOM中它显示为空字符串而我无法获得所需的结果。

var assetPath ='<?php echo $assetPath; ?>';
var num ='<?php echo $count; ?>';

(function($) {
 $(document).ready(function(){
$('.pager-top,.pager-bottom').bootpag({
    total: assetPath,
    page: 1,
    maxVisible: 5,
    leaps: true,
    firstLastUse: true,
    first: '←',
    last: '→',
    wrapClass: 'pagination',
    activeClass: 'active',
    disabledClass: 'disabled',
    nextClass: 'next',
    prevClass: 'prev',
    lastClass: 'last',
    firstClass: 'first'
}).on("page", function(event, num){
    $.ajax({
            url: "assetPath?pageNumber="+num,
            }).done(function(data) {
            $("#productResults").html( data );
             });
});
})( jQuery );
});

2 个答案:

答案 0 :(得分:2)

基本上,如果Php变量确实保存了值并且数据确实存在于其中,那么通过使用这种代码var assetPath ='<?php echo $assetPath; ?>';就可以了。在测试进入js环境之前,尝试回显到从服务器端发送的变量的页面,看看数据是否存在。对于ajax的东西,请确保使用data属性将数据发送到服务器端端点,请参阅以下示例:

var assetPath ='<?php echo $assetPath; ?>';
var num ='<?php echo $count; ?>';

$.ajax({
    type : 'POST',
    url: assetPath,//<-- is it this came from variable assetPath??
    data : {
     pageNumber : num,
    }
}).done(function(data) {
    $("#productResults").html( data );
});

在服务器端,假设assetpath保留值process.php

 $_POST['pageNumber']; //<-- retrieve data sent from ajax

如果您在上面的代码之后echo $_POST['pageNumber'];,那么这个值将在ajax的成功/完成块中可用:

.done(function(data) {
  // data is a data sent from server side
  $("#productResults").html( data );
});

答案 1 :(得分:0)

只需将您的变量放入$(document).ready(function(){

即可
(function($) {
 $(document).ready(function(){

var assetPath ='<?php echo $assetPath; ?>';
var num ='<?php echo $count; ?>';

$('.pager-top,.pager-bottom').bootpag({
    total: assetPath,
    page: 1,
    maxVisible: 5,
    leaps: true,
    firstLastUse: true,
    first: '←',
    last: '→',
    wrapClass: 'pagination',
    activeClass: 'active',
    disabledClass: 'disabled',
    nextClass: 'next',
    prevClass: 'prev',
    lastClass: 'last',
    firstClass: 'first'
}).on("page", function(event, num){
    $.ajax({
            url: "assetPath?pageNumber="+num,
            }).done(function(data) {
            $("#productResults").html( data );
             });
});
})( jQuery );
});

希望这会奏效:)

相关问题