如何使用AJAX在页面中加载功能?

我知道我的问题很愚蠢,但是我需要你的帮助。

我有一个php文件(例如index.php),其中包含(function.php)。在文件 function.php 中,我有一个函数(例如function Jokes(){....})。我想使用AJAX在我的页面中加载此功能,但是我不知道该怎么做......

我找到了一些简单的解决方案(我使用Jquery加载功能),但这不是我想要的,因为我必须使用单独的文件。

$('#jokes').load('jokes.php');

But I need something like:

$('#jokes').load('function.php','jokes()');

Any help or ideas? It will be appreciated.

P.S: Sorry for my bad English...))

The browser (and thus Ajax) can only make HTTP requests to the server.

It cannot execute specific functions.

You would have to write server side code that would recognise a particular URL (e.g. to a script that only calls that function, or a script that decides which function to run based on the query string) and execute a particular function in response to a request to it.

No, it's impossible to do it this way. You must make a request to a url. You can't just invoke a specific function from a php file.

Build a url wrapper for the function you need.

Don't do that. Ajax is used to send or retrieve data, but what you are trying to do is to load a Javascript function defined in a PHP file (isn't it?). Instead, just define your Javascript function in a JS file and load it via a script (or, if it should be loaded dynamically, you may use an AMD loader like require.js)

If you want to load a PHP function in JS, then it's not possible. You may call that function and fetch its result instead, though.

It doesn't work like this.

$('#jokes').load('jokes.php');

does an http request to jokes.php. If you want to execute a specific function, you can use a parameter, like this:

$('#jokes').load('jokes.php?func=jokes');

From your php script, get 'func' and execute the proper function.

...
function jokes() {
   return 'some output';
}

...
$func='';
if (!empty($_REQUEST['func'])) {
  $func=$_REQUEST['func'];
}

if ($func=='jokes') {
  echo jokes();  
}

What you can do is make one AJAX file, e.g. ajaxfunctions.php where you divide the functions.

$('#jokes').load("ajax.php", { 'function': 'jokes' } );

In your PHP file ajax.php you can do this:

<?php
include 'function.php';
if (isset ($_POST['function']) && $_POST['function'] == 'jokes')
{
    echo jokes ();
}
?>

Does this help you?

You don't need AJAX for this. You want to put the Jokes() function in a JavaScript file, maybe called Jokes.js, include it in index.php and then call it normally in a JavaScript block in index.php.