如何从ajax调用php函数?

前端之家收集整理的这篇文章主要介绍了如何从ajax调用php函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我很熟悉如何让ajax去PHP页面执行一系列事情然后返回json数据.但是,是否可以调用驻留在给定页面中的特定函数

基本上我想要的是减少项目中的文件数量.所以我可以在一个页面中放置很多常用函数,然后只调用我想要的函数.

@H_502_6@ 对于ajax请求

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

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

2.单击按钮调用功能

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

3.点击按钮,在javascript中调用create function.

  1. <script>
  2. function create () {
  3. $.ajax({
  4. url:"test.PHP",//the page containing PHP script
  5. type: "post",//request type,dataType: 'json',data: {registration: "success",name: "xyz",email: "abc@gmail.com"}
  6. success:function(result){
  7.  
  8. console.log(result.abc);
  9. }
  10. });
  11. }
  12. <script>

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

  1. $regstration = $_POST['registration'];
  2. $name= $_POST['name'];
  3. $email= $_POST['email'];
  4.  
  5. if ($registration == "success"){
  6. // some action goes here under PHP
  7. echo json_encode(array("abc"=>'successfuly registered'));
  8. }

猜你在找的Ajax相关文章