在Javascript代码中调用php函数

时间:2014-05-27 09:20:01

标签: javascript php ajax

我知道之前已经问过这个问题,但他们都使用的是jQuery库,我只想使用Javascript,没有库,所以请耐心等待。

此链接显示从jQuery调用的PHP函数。

How can I call PHP functions by JavaScript?

代码正在调用显示图像的函数。

我有以下代码,我不了解如何从mainfile.php调用该函数,而不是函数.php。

mainfile.php中

<button id="btn">Click</btn>   // button that calls ajax file
<div id="div"></div>   // div where it should appear

<script>
    function loadXML(method, url, div, index)
    {
        var xmlhttp;

        try
        {
            xmlhttp = new XMLHttpRequest();
        }
        catch(e)
        {
            try
            {
                xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch(e)
            {
                alert('sorry');
            }
        }

        xmlhttp.onreadystatechange = function()
        {
            if( xmlhttp.readyState === 4 && xmlhttp.status === 200 )
            {
                if( index === null || index === 'undefined' || xmlhttp === '')
                {
                    document.getElementById(div).innerHTML = xmlhttp.responseText;
                }
            }
        };

        xmlhttp.open(method, url, true);
        xmlhttp.send(null);
    }

    document.getElementById('btn').addEventListener('click', function()
    {
        loadXML('GET', 'imgs.php', 'div', null);
    }, false);
</script>

的functions.php

<?php

    function getImgs($dir, $type)
    {
        $images = glob($dir . $type);

        print_r($images); // for now i'm printing the array the way it is to see the function work
    }
    getImgs('images/', '.*JPG');   // calling function from php file works

?>

我想从mainfile.php中调用函数而不使用任何jQuery库,只使用普通的Javascript,应该可以考虑使用Javascript编写库。我不知道从mainfile.php里面调用函数的位置。任何帮助将不胜感激。

我从php获取文件的原因是因为它更容易将它们加载到DOM中,我需要创建一个图库,所以我想知道是否可以在加载图像时操纵图像使用AJAX的DOM。

2 个答案:

答案 0 :(得分:1)

您只能通过向php页面发出AJAX请求,同时传入参数来初始化该函数。

这意味着您的AJAX将发送例如&#34; functionName&#34;到php页面&#34; functionsListPage.php&#34;

GET将被收到:

 if (isset($_GET['functionName']))
    functionExec();

这是唯一的方法,因此您不会直接从客户端调用,但是您要向服务器指示要运行预定义的请求。

您无法直接从客户端调用PHP函数。

答案 1 :(得分:0)

这就像@Pogrindis的答案,但我认为需要这样解释

可以使用简单的JavaScript进行一些解决方法!

您需要做的是在xmlhttp.open();

之后的JavaScript中的以下内容
var functionname = getImgs;
xmlhttp.open();
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send(functionname);

这样做很简单:它将数据发送到服务器,因此php文件可以获取此参数!

在您调用的php文件中,您需要这样的内容:

if( isset($_POST['functionname']) )
{
    if($_POST['functionname']) == 'getImgs'
    {
        getImgs();
    }
}

当然,在这种情况下,您需要确保使用post发布数据,如果您要使用get,则需要将php更改为$_GET }

注意:现在这完全不安全!没有逃避即将到来的数据和其他任何事情。