使用通用ajax javascript调用任何php函数而不使用jQuery

Bob*_*iet 1 javascript php ajax json

我搜索了很多主题,但找不到合适的答案.我的目标是有一个HYML超链接,它调用在PHP页面上运行AJAX post请求的Javascript函数来运行PHP函数,可选地包含任意数量的参数.许多主题为特定功能(具有特定名称)解决了这个问题.我想概括AJAX post请求使用相同的函数来调用所有类型的PHP函数.

这就是我所拥有的,但它在PHP脚本中出错......

HTML:

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

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
    }));
}
Run Code Online (Sandbox Code Playgroud)

在JavaScript的我质疑JSON.stringify()setRequestHeader()如果在这种情况下正确使用.

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...
}
Run Code Online (Sandbox Code Playgroud)

在PHP我正在质疑,header('Content-Type: application/json')因为它已经在Javascript中定义了.但主要的问题是:如何编写PHP代码来调用PHP函数?顺便说一句:当我打印echo $post它时会发出警告:json_decode()期望参数1为字符串,给定数组...

squ*_*eim 5

PHP手册状态$_POST超全局变量只包含交论据类型的POST数据application/x-www-form-urlencodedmultipart/form-data.

当使用application/x-www-form-urlencoded或multipart/form-data作为请求中的HTTP Content-Type时,通过HTTP POST方法传递给当前脚本的关联变量数组.

但是,您尝试使用类型的主体发送发布请求application/json.

要阅读原始的身体在PHP中,你可以做这个:

$postdata = file_get_contents("php://input");
Run Code Online (Sandbox Code Playgroud)

这将为您提供整个请求正文的字符串.然后,您可以使用json_decode此字符串来获取所需的JSON对象.

至于调用请求中提供的函数的部分,call_user_func_array将完成工作.这是否是你应该做的事情是一个完全独立的问题.据我所知,您正在研究路由器和控制器的概念.

我写了一个我想你想做的简单片段:

<?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;
}

?>
Run Code Online (Sandbox Code Playgroud)