使用ajax时出现500内部服务器错误

500 internal server error when using ajax

本文关键字:内部 服务器 错误 ajax 使用      更新时间:2023-09-26

我在进行ajax调用时收到一个500内部服务器错误。

以下是进行调用的javascript/jquery:

$.ajax({url: 'ServicesAjaxHandler.php',
        data: {action: 'add'},
        type: 'post',
        success: function(output) {
            alert(output);
        },
        error: function (xhr, ajaxOptions, thrownError) {
           alert(xhr.status);
           alert(xhr.responseText);
           alert(thrownError);
        }
    });

这里是被调用的php文件:

<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'add' : add($_POST);break;
    }
}
public function add($data) {
    return 'test';
}
?>

xhr.responseText不返回任何内容。

我的PHP代码中是否存在导致此错误的问题?

在使用函数之前定义它们,例如:

function add($data) {
    return 'test';
}
if(isset($_POST['action']) && !empty($_POST['action'])) {
    $action = $_POST['action'];
    switch($action) {
        case 'add' : add($_POST);break;
    }
}

使用关键字public用于面向对象的应用程序,如果您有这样的设置:

class Test_Class { 
    public function add($data) {
        return 'test';
    }
}

使用关键字public是可以接受的,但由于您没有在函数交互中使用对象,因此删除工作集的关键字

尝试将public function更改为仅function

function add($data) {
    return 'test';
}