我想从jquery ajax( $.ajax({}) )
我的ajax代码在index.php中,php用户定义函数在functions.php
中两者都在同一个文件夹中
这是我的index.php代码
<html>
<head>
<script src="headerfiles/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function()
{
$("#display").click(function()
{
var mobile=$("#mobile").val();
$.ajax({
method:"post",
url:"functions.php",
success:function(name){alert(name);}
});
});
});
</script>
</head>
</body>
<input type="text" id="mobile" name="mobile" />
<input type="button" id="display" name="display" value="Display" />
</body>
</html>
和functions.php代码是
function fetch_name($mobile)
{
$name="my query............"
echo $name;
//or
return $name;
}
我想在index.php页面中显示名称
答案 0 :(得分:2)
你可以这样做
在js中添加:
data:{fc : 'fetch_name'};
在php中
$fc = $_POST['fc'];
$fc();
function fetch_name($mobile)
{
$name="my query............"
echo $name;
//or
return $name;
}
答案 1 :(得分:0)
根据你的脚本 Html: -
<html>
<head>
<script src="headerfiles/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function() {
$("#display").click(function(e)
{
var postData = $('#mobile').val(); // Data which you may pass.
var formURL = 'function.php'; // Write callback script url here
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert(data);
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
});
});
</script>
</head>
</body>
<input type="text" id="mobile" name="mobile" />
<input type="button" id="display" name="display" value="Display" />
</body>
</html>
在function.php中: -
<?php
// Post Value
$mobile = isset($_POST['mobile']) ? $_POST['mobile'] : '';
fetch_name($mobile);
function fetch_name($mobile) {
echo $mobile;
// Your function body goes here.
exit;
}
?>
答案 2 :(得分:0)
//In your ajax send a post param
$.ajax({
method:"post",
url:"functions.php",
data: {
'foo': 'function_name',
},
............
.................
In your functions.php
//capture the post param foo to get the function name
//set it to null if its not sent
$foo = isset($_POST['foo']) ? $_POST['foo'] : null;
//if foo is set call the function
if($foo){
$foo();
}
P.S我不知道你为什么要调用functions.php中的函数,而你可以从index.php中调用它并包含function.php。