Javascript 使用jqueryajax的PHP函数?
我有一个关于PHP函数、jQuery和AJAX的问题。 如果我的php索引中有这样一个按钮:Javascript 使用jqueryajax的PHP函数?,javascript,php,jquery,ajax,function,Javascript,Php,Jquery,Ajax,Function,我有一个关于PHP函数、jQuery和AJAX的问题。 如果我的php索引中有这样一个按钮: <input type="submit" value="Download" id="download"/> $(document).ready(function(e) { $("#download").click(function(){ $.ajax({ type: "GET", url: "dubs.php"
<input type="submit" value="Download" id="download"/>
$(document).ready(function(e) {
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
});
});
});
我如何告诉AJAX请求选择第二个函数
我不知道如何做到这一点,我已经用
“success:first()”
或“success:function(){first()}”
尝试过了,但没有效果。在ajax中传递一些参数,以确定您希望像这样使用哪个函数
$("#download").click(function(){
$.ajax({
type : "POST",//If you are using GET use $_GET to retrive the values in php
url : "dubs.php",
data : {'func':'first'},
success: function(res){
//Do something after successfully completing the request if required
},
error:function(){
//If some error occurs catch it here
}
});
});
在php文件中
您可以通过ajax检索data
send中的值,并执行以下操作
if(isset($_POST['func']) && $_POST['func']=='first'){
first();
}
else{
second();
}
这就是我要做的: 您的PHP:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
if (isset($_POST["first"])) first();
if (isset($_POST["second"])) second(); //add 'else' if needed
?>
然后,根据发送到
$.post
的对象,php文件将知道要运行哪个函数。在php页面中尝试以下操作:
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
switch($_POST['func']) {
case "first":
first();
break;
case "second":
second();
break;
default:
// Define your default here }
?>
func
变量将告诉php要运行哪个函数
})) 为什么不尝试传递
数据:{func:f1}
并在php端获取它,如果f1
存在,则启动第一个函数。尽管您可以发送多个:
jQuery:
$(“#下载”)。单击(函数(e){
e、 preventDefault();//JS
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
data: {'function':'first'}
});
});
PHP
call_user_func($_GET['function']);
注
小心使用$\u GET
参数,最好先检查$\u GET
的内容,谢谢你指出@Laz Karimov。我已经更新了答案。你还需要一个success
函数来处理返回的数据。谢谢它可以工作,但还有一个小问题:你知道为什么它会变成else语句吗对于if?它运行second();而不是first();但我不明白它为什么会这样做。您可以尝试使用var_dump($_POST['func'])来查看与之关联的任何空格吗?如果是这样,请在php中使用trim()来删除空格。在使用var_dump()时,在ajax中使用相同的数据键。意思是如果数据:{'func':'first'},然后是var_dump($_POST['func'])$\u POST中的数据键相同。我认为您已经更改了ajax中的键
$(document).ready(function(e) {
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
data: {'func':'first'}
});
});
$("#download").click(function(e){
e.preventDefault(); // <----stops the page refresh
$.ajax({
type: "GET",
url: "dubs.php",
data:{'func':'f1'}
});
});
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
if(isset($_GET['func']=='f1'){
first();
}else{
second();
}
?>
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
data: {'function':'first'}
});
});
call_user_func($_GET['function']);