提问者:小点点

在一个PHP文件上处理多个ajax


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

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数据。

但是如何在一个PHP中处理多个$AjaxPOST。

对于每个ajax数据,我都包含了一个唯一的标识符类型:,这将作为PHP接收到的ajax的参考

但我不确定如何正确地编写PHP代码来处理提交的$_POST类型。

<?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
      }
 ?>

共2个答案

匿名用户

每个案例发送一个操作,

例如。

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

在每种情况下,发送不同的操作,然后在PHP中使用$_post/$_get['action']进行检查

因此可以执行switch语句

例如。

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

匿名用户

你可以这样做:

switch(true) {
  case textA.test(input):
    // CASE A
      $ajax ({
        type:"post",
        url:"process.php",
        data: {input:input,age:age,city:city,type:"typeA"},
        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:"typeB"},
        success: function(html){alert(html);} });
      break;
 case ...
 }

然后在PHP中:

<?php

  switch($_POST['type']) { // or $_REQUEST['type']
    case 'typeA':
      // Type A handling code here
      break;
    case 'typeB':
      // Type B handling code here
      break;
  }