PHP函数与jQuery AJAX?
我有一个关于PHP函数,jQuery和AJAX的问题。 如果我的php索引中有一个按钮,如下所示:
我有另一个PHP文件(dubs.php),其中包含:
我的jQuery,像这样:
$(document).ready(function(e) { $("#download").click(function(){ $.ajax({ type: "GET", url: "dubs.php", }); }); });
如何告诉我的AJAX请求选择第二个函数?
我不知道如何做到这一点,我已经用"success: first()"
或者"success: function(){ first() }"
尝试它,但这不起作用。
在你的ajax中传递一些参数来识别你想要使用的function
$("#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
发送中的值并执行以下操作
if(isset($_POST['func']) && $_POST['func']=='first'){ first(); } else{ second(); }
这就是我要做的:
你的PHP:
你的jQuery:
$.post("dubs.php", {"first":true}, function(result) { $("#someDivToShowText").text(result); });
然后,根据您发送到$.post
的对象,php文件将知道要运行的函数。
在PHP页面中尝试这个:
这在你的JS中:
$(document).ready(function(e) { $("#download").click(function(){ $.ajax({ type: "GET", url: "dubs.php", data: {'func':'first'} }); });
func
变量将告诉php运行哪个函数!
});
为什么不尝试传递data:{func:f1}
并在php端获取它,如果f1
在那里则触发第一个函数。 虽然你可以发送多个:
jQuery的:
$("#download").click(function(e){ e.preventDefault(); // <----stops the page refresh $.ajax({ type: "GET", url: "dubs.php", data:{'func':'f1'} }); });
PHP:
JS
$("#download").click(function(){ $.ajax({ type: "GET", url: "dubs.php", data: {'function':'first'} }); });
PHP
call_user_func($_GET['function']);
注意
注意$_GET
参数,最好先检查$_GET
的内容