使用AJAX在单独的文件中调用php函数


Calling a php function in a separate file using AJAX

我一直在写一个货币转换器,需要使用jQuery和AJAX来发送往来货币,以及要转换为PHP文件的值,PHP文件会返回转换后的值。

我的解决方案基于:如何通过JavaScript调用PHP函数?然而,它似乎不起作用。

jQuery代码:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
function exchange(from, to, amount){
    alert("got to here"); //this alert shows
    jQuery.ajax({
        type: "POST",
        url: 'exchange_caller.php',
        dataType: 'json',
        data: {functionname: 'exchange_rate_convert', arguments:["USD", "EUR", 1]},
        //dummy pass values
        success: function (obj, textstatus){
            if( !('error' in obj)){
                answer = obj.result;
                alert(answer);      //neither of these alerts show
                alert('anything');
            }
            else{
                console.log(obj.error);
                alert("got an error"); //this alert doesn't show
            }
        }
    });
    alert("passed the block"); //this alert shows
    return false;               //return false so the page doesn't refresh
}</script>

php文件"exchange_caller.php"中的代码(设置为伪代码)。

<?php header('Content-Type: application/json');
$aResult = array();
if(!isset($_POST['functionname'])){
    $aResult['error'] = 'No function name!';
}
if(!isset($_POST['arguments'])){
    $aResult['error'] = 'No function arguments';
}
if(!isset($aResult['error'])){
    switch($_POST['functionname']){
        case 'exchange_rate_convert':
            if(!is_array($_POST['arguments']) || (count($_POST['arguments']) < 3)){
                $aResult['error'] = 'Error in arguments!';
            }
            else{
                $aResult['result'] = exchange_rate_convert($_POST['arguments'][0], $_POST['arguments'][1], $_POST['arguments'][2]);
            }
            break;
        default:
            $aResult['error'] = 'Not found function '.$_POST['functionname'].'!';
            break;
    }
}
echo json_encode($aResult);
function exchange_rate_convert($from, $to, $amount){    //function to run
    //dummy code, just return 2 for now
    $value = 2;
    return $value;
}?>

当运行此操作时,我会收到"到达此处"answers"通过块"错误消息,但当我应该返回结果时,这两条消息都没有。

如有任何帮助,我们将不胜感激。

谢谢。

我用发布的代码设置了文件,它们按预期运行。

看起来还有另一个与所提供的代码无关的问题。

我建议确保您的托管环境没有问题。查阅服务器日志,查看是否有其他问题阻碍了您的请求得到满足,并在另一个浏览器中对其进行测试,以确保没有插件或扩展程序干扰它。