使用jQuery .load()将参数传递给php函数并调用它

时间:2011-12-29 23:56:13

标签: php jquery

这是我的jQuery .load函数。我想要做的是使用jQuery传递的值运行php函数。我想我只是不明白如何将值与jQuery传递给服务器。我可能需要使用.get或.post吗?请指教。

$(document).ready(function(){
  $("#scotland").click(function() {
    $("#Main").load('thumbs.php #Main', $path=./scotland);
  });
});

jQuery脚本所针对的php div。

<div id="main">
<?php
function thumbnailload($path)
{
$dir_handle = @opendir($path) or die("Unable to open folder");
while (false !== ($file = readdir($dir_handle))) {

if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $file)){
echo "<a href='$path/$file'><img class='thumbnail' src='$path/thumbs/thumb_$file' alt='$file'></a>";
}
}
closedir($dir_handle);
}
thumbnailload($path);
?>
</div>

2 个答案:

答案 0 :(得分:6)

通常在早期遇到这种问题,不知道如何与客户端语言(JavaScript)交互到服务器端(PHP)。但是,我们走了!

对于页面“thumbs.php”接收参数,您必须通过GET或POST发送数据。

使用Javascript:

$(document).ready(function(){
    $("#scotland").click(function() {
        $("#Main").load('thumbs.php', {'path': 'scotland'});
    });
});

thumbs.php

<div id="main">
    <?php
        if(!empty($_REQUEST['path'])) { // i used $_REQUEST because it receives the data from POST or GET.
            $path = $_REQUEST['path'];
            $dir_handle = @opendir($path) or die("Unable to open folder");
            while (false !== ($file = readdir($dir_handle))) {
                if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $file)) {
                    echo "<a href='$path/$file'><img class='thumbnail' src='$path/thumbs/thumb_$file' alt='$file'></a>";
                }
            }
            closedir($dir_handle);
        } 
    ?>
</div>

如果未传递数据,则jquery中的方法.load()使用GET请求类型。在我们的例子中,我传递数据({'path':'scotland'}),因此请求的类型为POST。

有用的链接

我希望我有所帮助=]

答案 1 :(得分:1)

将jQuery脚本更改为:

$(document).ready(function(){
  $("#scotland").click(function() {
    $("#Main").load('thumbs.php #Main', {'func': 'thumbnailload', 'path': './scotland'});
  });
});

并将PHP代码更改为:

<div id="main">
<?php
$func = $_GET['func'];
switch($func){
    case 'thumbnailload':
       thumbnailload($_GET['path']);
    break;
}

function thumbnailload($path)
{
$dir_handle = @opendir($path) or die("Unable to open folder");
while (false !== ($file = readdir($dir_handle))) {

if(ereg("(.*)\.(jpg|bmp|jpeg|png|gif)", $file)){
echo "<a href='$path/$file'><img class='thumbnail' src='$path/thumbs/thumb_$file' alt='$file'></a>";
}
}
closedir($dir_handle);
}
thumbnailload($path);
?>
</div>

表示参考:http://api.jquery.com/load/