在AJAX中使用php文件的最佳实践

时间:2014-08-31 20:56:24

标签: javascript php jquery ajax

我正在开始用php进行web开发,我正在测试jQuery ajax调用php文件来运行函数。但我注意到每次用AJAX POST方法调用它时,php文件都会加载到资源中。防止这种情况发生的最佳解决方案是什么?另外,从php中的单个文件执行多个函数调用(我习惯于在c#世界中调用Web服务或Web方法)时,是否有更好的编码实践?

test.php的

<?php
    if($_POST['action']=='test'){
        $arr = array(
            'stack'=>'overflow',
            'key'=>'value'
        );
        echo json_encode($arr);
   }
?>

scripts.js中

function postTest(){
    var data = {
        action: 'test'
    };
    $.ajax({
        type: "POST",
        url: "test.php",
        dataType: 'json',
        data: data,
        success: function(result){
            console.log(result)
        }
    });
}

更新: 我改变了我的代码,使用数据变量作为ajax调用中的对象。 然而,最初的问题仍然存在。如何在php文件中使用函数而不将其加载到浏览器中的每个ajax调用的站点资源中?

谢谢。

2 个答案:

答案 0 :(得分:0)

如果你注意到php块永远不会被执行,那么你就错误地传递了数据。试试这个:

function postTest(){
  var data = {
    'action': 'test'
  };
  $.ajax({
    type: "POST",
    url: "test.php",
    dataType: 'json',
    data: data,
    success: function(result){
      console.log(result)
    }
  });
}

答案 1 :(得分:0)

JSON.stringify对你不利,在这里。

为了证明这一点,你可以将print_r($_POST)放在你的php脚本中,看看console.log(result)给你的是什么。

要解决此问题,您只需将数据放入$.ajax()块:

即可
function postTest(){
    $.ajax({
        type: "POST",
        url: "test.php",
        dataType: 'json',
        data: {
           action: 'test'
        },
        success: function(result){
            console.log(result)
        }
    });
}