简体   繁体   English

使用Javascript AJAX发布请求调用任何PHP函数

[英]Call any PHP function using a Javascript AJAX post request

I've searched around a lot of topics, but couldn't find the answer. 我搜索了很多主题,但找不到答案。 My goal is to have a HTML hyperlink calling a Javascript AJAX post request on a PHP page to run a PHP function (optionally with any amount of arguments). 我的目标是让HTML超链接在PHP页面上调用Javascript AJAX发布请求以运行PHP函数(可选地,可以包含任意数量的参数)。 A lot of topics solved this problem for defined functions (with a specific name). 许多主题解决了定义函数(使用特定名称)的问题。 I want to generalize the AJAX post request function in order to pass the PHP function name to the AJAX request to call it, so I can define in Javascript what PHP function to call. 我想对AJAX发布请求函数进行概括,以便将PHP函数名称传递给AJAX请求以对其进行调用,因此我可以在Javascript中定义要调用的PHP函数。

This is what I have, but it goes wrong at the PHP script... 这就是我所拥有的,但是在PHP脚本中却出错了...

The HTML: HTML:

<a onclick="call_php('php_function_name', ['arg_1', 'arg_2']);">call</a>
<p id="demo"></p>

The Javascript: Javascript:

function call_php(fname, args) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById('demo').innerHTML = this.responseText;
        }
    };
    xhttp.open('POST', 'includes/functions.php', true);
    xhttp.setRequestHeader('Content-type', 'application/json');
    xhttp.send(JSON.stringify({
        'fname': fname,
        'args': args
    }));
}

At the Javascript I'm questioning the JSON.stringify() and setRequestHeader() if it is used correctly in this case. 在Javascript上,我要询问JSON.stringify()setRequestHeader()是否在这种情况下正确使用。

The PHP, which should call a function in it's file: PHP,应该在文件中调用一个函数:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    //header('Content-Type: application/json');
    $post = json_decode($_POST/*, true*/);
    // DO SOMETHING TO CALL: fname(...args);
}
function php_function_name(arg_1, arg_2) {
    // A FUNCTION...
}

At the PHP I'm questioning the header('Content-Type: application/json') since it's already defined at the Javascript. 在PHP上,我正在质疑header('Content-Type: application/json')因为它已经在Javascript中定义了。 But the main question is: how to write the PHP code to call the PHP function? 但是主要的问题是:如何编写PHP代码来调用PHP函数? By the way: when I print echo $post it gives a warning: json_decode() expects parameter 1 to be string, array given... 顺便说一句:当我打印echo $post它发出警告:json_decode()期望参数1为字符串,给定数组...

The PHP Manual states that the $_POST super global variable only contains the post arguments for post data of type application/x-www-form-urlencoded or multipart/form-data . PHP手册指出 $_POST超级全局变量仅包含application/x-www-form-urlencodedmultipart/form-data类型的post数据的post参数。

An associative array of variables passed to the current script via the HTTP POST method when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request. 当在请求中使用application / x-www-form-urlencoded或multipart / form-data作为HTTP Content-Type时,通过HTTP POST方法传递给当前脚本的变量的关联数组。

However, you are trying to send a post request with the body of type application/json . 但是,您尝试发送带有application/json类型的正文的发布请求。

To read a raw body in PHP you can do this : 要读取PHP的原始内容,您可以执行以下操作

$postdata = file_get_contents("php://input");

This will give you a string of the entire request body. 这将为您提供整个请求正文的字符串。 You can then json_decode this string to get the desired JSON object. 然后,您可以json_decode此字符串以获取所需的JSON对象。

As for the part of calling a function supplied in the request, the call_user_func_array will do the job fine. 至于调用请求中提供的函数的部分, call_user_func_array可以很好地完成工作。 Whether or not that is something you should do is an entirely separate issue. 是否应该做那是一个完全独立的问题。 From what I understand, you are edging on on the concept of a router and a controller . 据我了解,您正在逐步了解路由器和控制器的概念。

I have writen a simple snippet of what I think you want to do: 我写了一个简单的代码片段,说明您想做什么:

<?php

switch ($_SERVER['REQUEST_METHOD']) {
  case 'POST':
    post_handler();
    return;
  case 'GET':
    get_handler();
    return;
  default:
    echo 'Not implemented';
    return;
}

function post_handler() {
  $raw_data = file_get_contents("php://input");
  $req_body = json_decode($raw_data, TRUE);
  call_user_func_array($req_body['function'], $req_body['args']);
}

function get_handler() {
  echo 'This page left intentionally blank.';
}

function some_function($arg1, $arg2) {
  echo $arg1.' '.$arg2;
}

?>

Comment json_decode and output your $_POST by calling print_r ($_POST); 注释json_decode并通过调用print_r($ _POST)输出$ _POST; you should see your data structure, if it is a simple array with data keys and values then you don't have to decode it but if the array have a single column and it's value is your data then take it's key and use it to decode the content 您应该看到您的数据结构,如果它是具有数据键和值的简单数组,则不必解码它,但是如果该数组只有一列并且它的值是您的数据,则使用它的键并使用它来解码内容

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM