在单个PHP文件上处理多个Ajax [英] handle multiple ajax on a single PHP file

查看:41
本文介绍了在单个PHP文件上处理多个Ajax的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 js 开关声明,用于检查提交的文本中是否存在特定的字符串.

I have a js switch declaration that checks if a specific string is present in the submitted text.

var textA= //regex
var textB= //regex

switch(true) {
  case textA.test(input):
    // CASE A
      $ajax ({
        type:"post",
        url:"process.php",
        data: {input:input,age:age,city:city,type:type},
        success: function(html){alert(html);} });
      break;
  case textB.test(input):
    // CASE B
      $ajax ({
        type:"post",
        url:"process.php",
        data: {input:input,width:width,height:height,type:type},
        success: function(html){alert(html);} });
      break;
 case ...
 }

通常,我会创建一个专用的 php 文件来处理每个 $ ajax 的POST数据.

normally, i would create dedicated php file to handle the POST data for each of $ajax.

但是我如何在单个 php 中处理多个 $ ajax POST.

but how can i handle multiple $ajax POST in a single php.

我为每个ajax数据都包含一个唯一的标识符 type:,这将是我对PHP正在接收的ajax的引用

i included a unique identifier type: for each ajax data, this will be my reference as to what ajax is being received by my PHP

但是我不确定如何正确编码PHP以处理提交的$ _POST类型.

but im not sure how to properly code PHP to handle the submitted $_POST type.

<?php
      //get post type from submitted AJAX
      $type = $_POST;

      switch($type) {
        case 0:
          $type= "caseA"
          //some code here
        case 1:
          $type= "caseB"
          // some code here
      }
 ?>

推荐答案

根据情况发送操作,

例如

$.ajax({
   url: 'path/to/file.php',
   type: 'POST / GET',
   data: {action: 1, data:myObject}
});

每种情况下,发送不同的操作,然后在PHP中使用 $ _ POST/$ _GET ['action']

Every case, send a different action, then in PHP check that with $_POST / $_GET['action']

因此您可以执行 switch 语句

例如

switch($_POST / $_GET['action']) {
   case 1:
       //do something
       break;
}

这篇关于在单个PHP文件上处理多个Ajax的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆