如何从ajax调用php函数? [英] How to call a php function from ajax?

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

问题描述

我熟悉如何使ajax进入php页面并执行一系列操作,然后返回json数据.但是,可以调用驻留在给定页面中的特定函数吗?

I am familiar of how to get ajax to go to a php page an execute a series of things and then return json data. However is it possible to call a specific function which resides in a given page?

基本上我想要的是减少项目中的文件数.因此,我可以将很多常用功能放在一页中,然后只需调用当前所需的任何功能即可.

Basically what I want is to reduce the number of files in a project. So I can put a lot of common functions in one page and then just call whatever the function that I want at the moment.

推荐答案

对于ajax请求

1.在您的网页中包含Jquery库. 例如:

1.Include Jquery Library in your web page. for eg:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

2.单击按钮调用功能

2.Call a function on button click

<button type="button" onclick="create()">Click Me</button>

3.在单击按钮的同时,调用javascript中的create函数.

3.while click on button ,call create function in javascript.

    <script>
    function create () {
          $.ajax({
            url:"test.php", //the page containing php script
            type: "post", //request type,
            dataType: 'json',
           data: {registration: "success", name: "xyz", email: "abc@gmail.com"}
            success:function(result){

             console.log(result.abc);
           }
         });
     }
<script>

在服务器端的test.php文件中,应读取操作POST参数和相应的值,并以php格式执行操作,并以json格式返回,例如

On the server side test.php file, the action POST parameter should be read and the corresponding value and do the action in php and return in json format e.g.

$regstration = $_POST['registration'];
$name= $_POST['name'];
$email= $_POST['email'];

if ($registration == "success"){
 // some action goes here under php
 echo json_encode(array("abc"=>'successfuly registered'));
}

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

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