Javascript 如何为PHP部件处理指定ajax调用
我使用ajax调用从php文件中获取信息,我对这些是新手。我的html中有7个元素需要单击并触发ajax调用。我创建了7个不同的php文件来处理这些ajax调用,如下所示: html部分: 每个元素有7个java部件。然后为每个元素添加7个php部分。 我要问的是,是否有任何方法可以在一个php文件中处理这些调用。 (例如,为ajax调用指定名称、变量或id,并在php文件中检查它是哪个调用)。 这样(在php中): 和PHP(../action.PHP) 和PHP(../action.PHP)Javascript 如何为PHP部件处理指定ajax调用,javascript,php,ajax,Javascript,Php,Ajax,我使用ajax调用从php文件中获取信息,我对这些是新手。我的html中有7个元素需要单击并触发ajax调用。我创建了7个不同的php文件来处理这些ajax调用,如下所示: html部分: 每个元素有7个java部件。然后为每个元素添加7个php部分。 我要问的是,是否有任何方法可以在一个php文件中处理这些调用。 (例如,为ajax调用指定名称、变量或id,并在php文件中检查它是哪个调用)。 这样(在php中): 和PHP(../action.PHP) 和PHP(../action.PHP)
有很多方法可以做到这一点,但一个简单的方法是使用如下类选择器简化代码:
<a style="cursor:pointer;" class='ajax-link' id="one" data-variable='1'></a>
<a style="cursor:pointer;" class='ajax-link' id="two" data-variable='2'></a>
然后在PHP中,类似于:
<?php
$variable = $_POST['variable'];
if ($variable == 1) {
}
if ($variable == 2) {
}
有很多方法可以做到这一点,但一个简单的方法是使用如下类选择器简化代码:
<a style="cursor:pointer;" class='ajax-link' id="one" data-variable='1'></a>
<a style="cursor:pointer;" class='ajax-link' id="two" data-variable='2'></a>
然后在PHP中,类似于:
<?php
$variable = $_POST['variable'];
if ($variable == 1) {
}
if ($variable == 2) {
}
首先,使用而不是直接连接的事件
其次,将单击的id/类传递给PHP脚本:
$("#one").click(function(){
$.ajax({
url: '../ajax.php?clickedButton=' + this.id,
第三,用PHP解析参数:
if (isset($_GET['clickedButton'])) {
switch($_GET['clickedButton']) {
case 'one':
/* ... */
break;
}
}
首先,使用而不是直接连接事件
其次,将单击的id/类传递给PHP脚本:
$("#one").click(function(){
$.ajax({
url: '../ajax.php?clickedButton=' + this.id,
第三,用PHP解析参数:
if (isset($_GET['clickedButton'])) {
switch($_GET['clickedButton']) {
case 'one':
/* ... */
break;
}
}
您只需将类添加到所有元素并使用一个函数就可以做到这一点
<a style="cursor:pointer;" id="one" class="ajax"></a>
<a style="cursor: pointer;" id="two" class="ajax"></a>
<a style="cursor: pointer;" id="three" class="ajax">></a>
.....
$(".ajax").on("click"i function() {
$.ajax({
url: "common.php?type=" + $(this).attr("id"),
dataType: 'html',
success: function(response) {
// handle response
}
})
});
>
.....
$(“.ajax”)。在(“单击”i函数()上{
$.ajax({
url:“common.php?type=“+$(this.attr(“id”),
数据类型:“html”,
成功:功能(响应){
//处理响应
}
})
});
common.php
<?php
if (!empty($_GET["type"])) {
// your code here
}
?>
您只需将类添加到所有元素并使用一个函数就可以做到这一点
<a style="cursor:pointer;" id="one" class="ajax"></a>
<a style="cursor: pointer;" id="two" class="ajax"></a>
<a style="cursor: pointer;" id="three" class="ajax">></a>
.....
$(".ajax").on("click"i function() {
$.ajax({
url: "common.php?type=" + $(this).attr("id"),
dataType: 'html',
success: function(response) {
// handle response
}
})
});
>
.....
$(“.ajax”)。在(“单击”i函数()上{
$.ajax({
url:“common.php?type=“+$(this.attr(“id”),
数据类型:“html”,
成功:功能(响应){
//处理响应
}
})
});
common.php
<?php
if (!empty($_GET["type"])) {
// your code here
}
?>