希望我能正确地提出这个问题,因为我知道我想要它做什么,但似乎无法从搜索中找到任何答案。
我有一个 func.php 页面,其中包含我的所有函数,我希望 ajax 使用该页面中的一个函数。
函数.php
function toptable()
{
echo"something happens in here";
}
索引.php
<?php include 'func.php'; ?>
<script type="text/javascript">
function check_username() {
uname=document.getElementById("username").value;
var params = "user_id="+uname;
var url = "topoftable()";
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: params,
beforeSend: function() {
document.getElementById("right").innerHTML= 'checking' ;
},
complete: function() {
},
success: function(html) {
document.getElementById("right").innerHTML= html ;
}
});
}
</script>
有道理吗?
最佳答案
它不是那样工作的。
您的 AJAX 请求应如下所示:
$(document).ready(function() {
//some even that will run ajax request - for example click on a button
var uname = $('#username').val();
$.ajax({
type: 'POST',
url: 'func.php', //this should be url to your PHP file
dataType: 'html',
data: {func: 'toptable', user_id: uname},
beforeSend: function() {
$('#right').html('checking');
},
complete: function() {},
success: function(html) {
$('#right').html(html);
}
});
});
还有你的func.php
:
function toptable()
{
echo 'something happens in here';
}
//here you can do some "routing"
$func = $_POST['func']; //remember to escape it
switch ($func) {
case 'toptable':
toptable();
break;
default:
//function not found, error or something
break;
}
还要检查我是否将 document.getElementById
更改为 jQuery 选择器 $('#...')
。
关于javascript - 使用ajax url调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19869146/