我经常看到这个问题,所以我根据我对这个概念的理解写了一个概括的答案,以便将未来类似类型的问题重定向到这里。
作为新手你应该知道的第一件事是,当你打开一个 PHP 页面时,PHP 代码是第一个由服务器执行,然后是 HTML 和 JavaScript 由浏览器。现在,当您与 HTML 元素进行交互时,例如更改输入框的内容或从下拉列表中选择选项甚至单击按钮等,这些动作/事件 可以被 JavaScript 检测到,但是 不是 PHP。因此,您需要一种让客户端 (JavaScript) 与服务器端 (PHP) 交互的方法。这种方式称为AJAX。
简单来说,AJAX 的作用是当用户在页面上执行任何操作(例如单击按钮)时,使用 events(和 event handlers)您可以捕获用户输入并通过 AJAX 将其传递给 PHP。
AJAX 的框架预览:
$.ajax({ // ajax block starts
url: 'send.php', // The PHP file that you want to send your user input to
type: 'POST', /*
by default the values will be sent as GET -
through address but if it's sensitive data,
use POST
*/
data: {data1: $('#textbox').val(), data2: $('#select').val()}, // The data to be sent
dataType: 'text', /*
Over here you set the type of response that will be sent
back by the PHP file. It could be 'text','html' or
if you have to send back values in array format
you can use'json' type
*/
success: function(data)
{
/*
This block will be called once the PHP file is executed and
the 'data' parameter here holds
the values returned from the PHP file
*/
}
});
如前所述,您可以在页面加载或与 HTML 元素交互时使用事件和事件处理程序调用 AJAX。
例如,我们有一个button:
<input type="button" id="button" value="Click" />
我们可以通过以下方式检测点击事件:
$('#button').click(function(){
// AJAX here will run on click of button
}
或者如果我们有一个select 下拉列表:
<select id="dropdown">
<option value=1>1</option>
<option value=2>2</option>
</select>
当您选择一个选项时,change 方法将被触发
$('#dropdown').change(function(){
// AJAX here will run on change of select
}
这里的哈希# 表示id 属性。您不能多次拥有相同的id,如果出现这种情况,您应该使用class 属性,然后使用带有如下类名的点.:
<input type="button" class="button" value="Click">
<input type="button" class="button" value="Click Again">
$('.button').click(function(){
//clicking any of the above button will trigger this code
}
既然你有几个按钮具有相同的类,那么函数如何知道哪个按钮被点击了?为此,您使用$(this)。 $(this) 是一个 jQuery 元素对象,它引用当前调用该方法的对象。
另一个需要注意的重点是,如果您加载了动态 HTML 元素,那么您需要添加一个 on() 事件处理程序。更多内容here.
现在最关键的部分是访问我们从 AJAX 传递的 PHP 中的值:
/*
This if block here detects if the request is sent through AJAX,
it's not necessary but use this if you want to prevent direct access
to this PHP file and allow it ONLY through AJAX.
*/
if ( !empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' )
{
/*
Now depending on the 'type' we set in our AJAX code,
we would have to call it by $_GET if the type is 'GET'
and $_POST if the type is 'POST', in the above we have
set it to POST so the following code demonstrates the same
*/
# So the data can be accessed as:
echo $_POST['data1'];
echo $_POST['data2'];
}
data1,data2 这里是标识符,我们通过它来引用 AJAX 中传递的值。
AJAX 中还有很多有用的功能,例如定期访问 PHP 文件 (timeout)、以数组格式返回数据 (json) 等。
或者,您也可以使用$.get 和$.post,它们再次基于 AJAX 的概念,但功能较少。