使用 ajax url 调用函数
using ajax url to call function
希望我能正确地问这个问题,因为我知道我想要它做什么,但似乎无法从搜索中找到任何答案。
我有一个 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 选择器 $('#...')
。
PHP 是服务器端,JS 是客户端。你需要在 ajax 请求中调用 PHP 脚本,而不是函数。
类似的东西
[...]
var url = "func.php";
$.ajax({
type: 'POST',
url: url,
[...]
功能.php
<?php
function toptable()
{
echo "something happens in here";
}
toptable();
?>
在这种情况下,ajax 请求的成功处理程序中的 html
参数将等于 "something happens in here"
。
有意义吗? - 不。你不能将PHP(一种服务器端技术)与Javascript(客户端)混合使用。可以使用 AJAX 请求服务器为您执行某些功能,但不能将函数名称用作 URL。您应该创建一个 PHP 页面来接受您的 AJAX 请求,执行该函数并返回结果,并在您的 AJAX 请求中使用该页面的 URL
相关文章:
- 是否可以将一个函数输入连接到另一个函数调用的文本
- 在输入字段上有两个函数调用,一个在Blur上,一个不在Angular中
- 如何在Javascript函数调用中循环变量
- Javascript:应为赋值或函数调用,但实际看到的却是表达式
- 如何远程检查JavaScript应用程序的函数调用堆栈
- javascript函数调用不起作用
- 为什么这个函数调用会破坏程序并导致未定义的变量
- 如何通过函数调用设置图像的src
- 从全局函数调用Ember控制器上的方法
- 为什么Jquery$.ajax在函数调用中触发所有statusCode,即使调用成功
- JavaScript函数调用(arg1)(arg2)
- 打印链接时,将javascript函数调用到链接中
- 在函数调用中封装数据除了隐藏数据之外还有什么优点
- 无法从JavaScript中的函数调用对象属性
- 对中的函数调用进行排序是回调的唯一方法
- 函数调用方法有什么用
- Javascript:JSHint:应为赋值或函数调用,但实际看到的却是表达式
- HTML5(Bootstrap)通过函数调用运行动画
- 函数调用不起作用
- 函数中的Javascript函数调用