从JavaScript Ajax调用器调用PHP函数 [英] Call a PHP function from a JavaScript Ajax caller

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

问题描述

我需要在php类中对我的php函数进行ajax调用.

I need to make an ajax call to my php function inside my php class.

文件夹如下:

controllers (folder)
-----User.php (php file)
View (folder)
-----js (folder)
---------myjavascriptfile.js

myjavascriptfile.js内的

我有这个:

inside that myjavascriptfile.js i have this:

$.ajax({
            type: "GET",
            url: "../controllers/User.php/newUser",
            data: { name: "John" }
        }).done(function( msg ) {
            alert( "Data Saved: " + msg );
        });

错误

我得到的错误是newUser不存在,尽管这是我的User.php

<?php

class User {
    function newUser($name){
        return "asdf";
    }
} 

对不起,如果这是一个愚蠢的问题,我在没有框架的情况下对PHP并不是很好:)

sorry if this is a silly question, i am not that good in php without frameworks :)

推荐答案

我可以看到您要执行的操作,并且我认为您对函数的调用方式有误解.将函数名称附加到URL不会强制php运行该函数. IE.击index.php/hello不会运行function hello() { echo "hello"; }

I can see what you're trying to do and I think you have a misunderstanding as to how functions are called. Appending the name of the function to the URL does not force php to run that function. I.e. hitting index.php/hello would not run function hello() { echo "hello"; }

这不是php的工作方式.

您必须做的是读取查询,即在PHP中读取正在传递的内容.如果您的URL是user.php/newUser,那么您必须读取正在传递的newUser以及某种switch语句否则(路由器,调用此控制器和此方法的核心文件等)告诉PHP运行该方法.

What you must do is read the query, i.e. in PHP read what is being passed in. If your url is user.php/newUser then you must read that newUser is being passed in, and in some sort of a switch statement or otherwise (a router, a core file that calls this controller and this method, etc) tell PHP to run that method.

在全局变量$_SERVER['PATH_INFO']中,您可以找到可以说的路线",即,如果您点击user.php/newUser,则该全局变量将返回/newUser

In the global variable $_SERVER['PATH_INFO'] you will find the "route" so to speak, i.e. if you hit user.php/newUser then that global will return /newUser

您可以执行以下操作,先读取函数名称(并去除斜线),然后在找到该函数的情况下运行该函数:

You could do something like this, which reads the function name (and strips out the slash), then runs the function if it can find it:

$methodName = str_replace("/", $_SERVER['PATH_INFO']);
if(function_exists($methodName)) $methodName();

这是一种非常简化的方法,广泛使用的框架显然要复杂得多.这应该使您了解如何读取所需路由的URL,以及如何测试方法是否存在,然后再使用动态名称调用方法.

This is a very simplified way of doing this and widely used frameworks are obviously much more complex. This should give you an idea of how to read the URL for the route expected though and how to test if a method exists and then call a method with a dynamic name as well..

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

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