使用AJAX将查询传递给函数(Javascript)
I'm trying to pass PHP Function parameters using Javascript (not JQuery) AJAX. Do I somehow add it to the javascript AJAX function send() ? Also i'm POSTing it to my PHP file.
The main thing is how do I use the XMLhttp.send() function to asynchronously call a PHP function while add parameters to the function.
我正在尝试使用Javascript(而不是JQuery)AJAX传递PHP函数参数。 我以某种方式将它添加到javascript AJAX函数send()? 我也将它发布到我的PHP文件中。 p>
主要的是我如何使用XMLhttp.send()函数异步调用PHP函数,同时向函数添加参数。 p> div>
It's not possible to call a specific PHP function from Javascript. The client doesn't know anything about the server side functions, and and the server side doesn't know anything about the client. jimbojw
's answer explains how to pass parameters into PHP and handle them in PHP. If you want to call a specific PHP function and return the results to the client, then you're going to have to have code to figure out which function to call on the server, or make a separate php file for each function you want to call.
If you want to go the first route, then you'd pass in something like an 'action' parameter, and then do this in your PHP file that contains the functions you want to call:
switch($_POST['action']) {
case 'foo':
foo($_POST['bar']);
break;
case 'foo2':
foo2($_POST['bar']);
break;
}
PHP will receive the request from JavaScript in the form of a POST or GET. Use the standard $_POST
and $_GET
superglobals to access the values.
edit - sorry, misunderstood the question
Yes, use XMLHttpRequest's send()
method. Ex:
var xhr = new XMLHttpRequest();
// ...
xhr.send("x=y&foo=bar");
Then, in PHP:
echo( $_POST['foo'] ); // echos "bar"