PHP Function with jQuery AJAX?
PHP Function with jQuery AJAX?
我有一个关于PHP函数,jQuery和AJAX的问题。如果我在php索引中有这样一个按钮:
<input type="submit" value="Download" id="download"/>
我有另一个php文件(dubs。php)包含这个
<?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
?>
和我的jQuery,像这样:
$(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文件
您可以检索data
通过ajax发送的值,并执行以下操作
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
?>
jQuery: $.post("dubs.php", {"first":true}, function(result) {
$("#someDivToShowText").text(result);
});
然后,根据您发送给$.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 }
?>
和这个在你的JS:
$(document).ready(function(e) {
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
data: {'func':'first'}
});
});
func
变量将告诉php运行哪个函数!
});
为什么不尝试通过data:{func:f1}
并将其放在php端,如果f1
在那里,则触发第一个函数。虽然你可以发送多个:
$("#download").click(function(e){
e.preventDefault(); // <----stops the page refresh
$.ajax({
type: "GET",
url: "dubs.php",
data:{'func':'f1'}
});
});
PHP: <?php
function first(){
echo 'first';
}
function second(){
echo 'second';
}
if(isset($_GET['func']=='f1'){
first();
}else{
second();
}
?>
JS
$("#download").click(function(){
$.ajax({
type: "GET",
url: "dubs.php",
data: {'function':'first'}
});
});
call_user_func($_GET['function']);
注意
注意$_GET
参数,最好先检查$_GET
相关文章:
- 在FrontEndphp-ajax-jquery中验证reCaptcha-google
- AJAX jquery json将数组发送到php
- 如何使用Ajax/jQuery设置cookie
- PHP/Ajax/jquery/JON-在Ajax Post之后将echo文本中的一部分作为变量返回
- 如何使用Ajax JQuery.ech()获取JSON值
- 使用springform时,如何在ajax/jquery中获取复选框值
- JSP AJAX jQuery填充表问题
- Piping Value: Ajax + JQuery
- 使用javascript Without Ajax/Jquery在特定行中启用文本框
- 在AJAX jQuery加载()之后运行jQuery代码
- 具有动态更新的实时标题 (AJAX+jQuery)
- ajax/jQuery Youtube 播放列表推送
- AJAX jQuery Avatar Uploading
- 全局变量 - AJAX jQuery
- Ajax jquery mysqli update
- 获取剩余时间和上传文件速度 - ajax jquery/js
- 使用ajax/jquery绑定Json数据
- TypeError Obj.root是未定义的ajax jquery
- 当数据类型为XML时,如何将url参数传递给AJAX jquery
- 在ajax Jquery之后无法获取隐藏字段的值