javascript - 使用ajax url调用函数

标签 javascript php jquery ajax

希望我能正确地提出这个问题,因为我知道我想要它做什么,但似乎无法从搜索中找到任何答案。

我有一个 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/

相关文章:

javascript - HTML 特殊字符在 js 中显示不正确

javascript - 在 VueJS 中渲染 [object HTMLTableElement]

php - 数组作为 PHP 中的队列

javascript - 基于多个下拉菜单返回数据

javascript - 为什么我的计算总计在 Acrobat 中无法正确更新?

javascript - React Hooks 中的正则表达式

javascript - $http get angularjs 无法传递参数?

php - PHPMailer 中的多个图像附件

javascript - jquery背景图片url失败

javascript - jQuery 获取段落内的数字,但不获取类中的数字