使用ajax url调用函数 [英] using ajax url to call function

查看:294
本文介绍了使用ajax url调用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hopefully I can ask this correctly cuz I know what I want it to do but can't seem to find any answers from searching.

我有一个func.php页面,其中包含所有功能,并且我希望ajax使用该页面中的一个功能.

I have a func.php page where I have all my functions and I want ajax to use one function from that page.

func.php

function toptable()
{ 
  echo"something happens in here";
}

index.php

index.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请求应如下所示:

Your AJAX request should look something like this:

$(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选择器$('#...').

Also check that I change document.getElementById to jQuery selector $('#...').

这篇关于使用ajax url调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆