将php文件与AJAX结合使用的最佳实践

Best practice for using php file with AJAX

本文关键字:最佳 结合 php 文件 AJAX      更新时间:2023-09-26

我开始使用php进行web开发,并测试jQuery对php文件的ajax调用以运行函数。但我注意到,每次使用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调用的浏览器中的站点资源中?

谢谢。

如果您注意到php块从未被执行,那么您传递的数据是错误的。试试这个:

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

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