【问题标题】:Multiple ajax calls on same file to execute different code in same file?同一文件上的多个ajax调用以在同一文件中执行不同的代码?
【发布时间】:2019-03-04 21:29:28
【问题描述】:

我对服务器端脚本和 ajax 还是很陌生。我想知道的是我可以对同一个文件进行多个 ajax 调用,但是通过我的 ajax 调用,只读取该文件中的某个脚本来执行该特定的 ajax 调用吗?我想知道这是因为当我进行 ajax 调用时,它会解析我的脚本的整个代码,它也在进行 ajax 调用,而不是我的其他 ajax 调用脚本中的特定代码。

现在,我可以通过简单地创建一个新文件并将我的 ajax 调用指向单独的文件来完全解决这个问题,但这不会被认为是糟糕的架构吗?例如,1 个对 editusers.js 的 ajax 调用另一个对 deleteusers.js 的 ajax 调用为什么不简单地将所有不同的 ajax 调用放在一个文件中?

这是我的代码,我使用的是带有服务器端渲染 PDO 而不是 mysqli 的引导数据表。第一个 ajax 调用是查询我的表中的所有记录,第二个 ajax 调用是关于在表本身中编辑用户记录的功能。但是,我停止了编辑用户记录功能,因为我想知道是否可以实现这一点?

HTML 和 JavaScript

<script type="text/javascript">
$(document).ready(function() {

    $('#userDetails').DataTable({
    	"scrollY": "400px",
    	"scrollCollapse": true,
    	"processing": true,
    	"serverSide": true,
    	"ajax": {
    		"url": "../user-actions-script.php",
    		"type": "post",
    	},
   		"deferRender": true,
 		oLanguage: {sProcessing: "<i class='fas fa-spinner fa-3x' id='loader'></i>"},
    });

	$(document).on('click', 'i.fas.fa-edit', function(e){
		$.ajax({
			url: '../user-actions-script.php',
			success: function(){
				console.log('works');
			}
		})
	});

});
</script>

<body>
	<div class="fluid-container">
		<header>
			<nav class="navbar navbar-expand-lg navbar-dark bg-dark"></nav>
		</header>
		<div class="container">
			<h2>User Actions</h2>

			<div class="userdetailsContainer">
				<table class="table table-dark table-striped table-bordered table-hover" id="userDetails">
					<thead>
						<!-- adding this in later -->
					</thead>
				</table>
			</div>
			<!-- Edit Actions Modal -->
			<!-- Modal -->
			<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
			  <div class="modal-dialog" role="document">
			    <div class="modal-content">
			      <div class="modal-header">
			        <h5 class="modal-title" id="exampleModalLabel"></h5>
			        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
			          <span aria-hidden="true">&times;</span>
			        </button>
			      </div>
			      <div class="modal-body">
			       	<div class="editHeader">
			       		<i class="fas fa-edit fa-2x"></i>
			       		<span>Edit User</span>
			       	</div>
			       	<div class="form-group">
			       		<form
			       			method="POST"
							
			       			>
				       		<label for="email">Email:</label>
				       		<input
				       		 	type="email"
								class="form-control"
								name="email"
				       		>
							<label for="fullName">Full Name:</label>
							<input
								type="text"
								class="form-control"
								name="fullName"
							>
							<label for="area">area:</label>
							<select
								class="form-control"
								name="area"
								id="area"
							>
								<?php include ("_global/includes/login_select_options-approved.php") ;?>
							</select>
							<label for="requestor">Requestor:</label>
							<select
								class="form-control"
								name="requestor"
								id="requestor"
							>
								<?php include ("_global/includes/select_options.php") ;?>
							</select>
  							</div>
			       		</form>
			        	<button
			        		type="submit"
			        		class="btn btn-primary">
			        		Save changes
			        	</button>
			       	</div>
			      </div>
			    </div>
			  </div>
			</div>
		</div>
	</div>
</body>

PHP PDO / Ajax 脚本

<?php 
	include "_global/includes/config.php";

	// Set all fetch requests as an object by default
	$dbo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

	// Custom Usergroups Inputs
	$admin = 'ADMIN';
	$emptyValues = '';
	$adminLive = 'ADMIN-live';
	$adminType = 'ADMIN_US_Type';
	$customusDomestic = 'US_domestic';
	$adminChina = 'China_admin';
	$adminIndia = 'India_admin';
	$adminCustom = 'ADMIN_custom';
	$customusaustinCulver = 'US_Austin_Culver';
	$customuschinaTokyo = 'US_China_Tokyo';
	$customcorkuaeBayarea = 'Cork_UAE_BayArea';
	$customchinashanghaiBeijing = 'China_Shanghai_Beijing';
	$adminselfMoves = 'ADMIN_selfmoves';
	$adminmilanVienna = 'ADMIN-milan-vienna';
	$custombayareaSeattle = 'Bayarea_Seattle_admin';
	$custombayareaCulver = 'ADMIN_Culver_Bay';
	$customculverSingapore = 'ADMIN_Culver_Singapore';
	$customcanada = 'ADMIN_canada';

	// Datatable serverside processing script
	$request = $_REQUEST;
	$columns = array(
		0 => 'name',
		1 => 'email',
		2 => 'usergroup',
		3 => 'user',
		4 => 'DateAdded'
	);

	// Prepare the query
	$sqlAll = 'SELECT mem_id, email, name, usergroup, user, DateAdded
			FROM plus_signuptestdata
			WHERE usergroup NOT IN (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
		 	GROUP BY email
		 	ORDER BY dateAdded DESC';

	$stmt = $dbo->prepare($sqlAll);

	// Execute the query
	$stmt->execute([$admin,$emptyValues,$adminLive,$adminType,$customusDomestic,$adminChina,$adminIndia,$adminCustom,$customusaustinCulver,$customuschinaTokyo,$customcorkuaeBayarea,$customchinashanghaiBeijing,$adminselfMoves,$adminmilanVienna,$custombayareaSeattle,$custombayareaCulver,$customculverSingapore,$customcanada]);

	// Count Rows
	$rowCount = $stmt->rowCount();
	// Fetch the query
	$totalData = $stmt->fetchAll(PDO::FETCH_ASSOC);
	$totalFiltered = $rowCount;


	$sqlAll = "SELECT mem_id, email, name, usergroup, user, DateAdded ";
	$sqlAll .= " FROM plus_signuptestdata ";
	$sqlAll .= " WHERE usergroup NOT IN (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	if(!empty($request['search']['value'])){
		$sqlAll .= " AND name LIKE '%".$request['search']['value']."%' ";

		$sqlAll .= " OR email LIKE '%".$request['search']['value']."%'";

	}
	// Order by with empty or without empty user string
	$sqlAll .=" ORDER BY ". $columns[$request['order'][0]['column']]." ".$request['order'][0]['dir']."  LIMIT ".$request['start']." ,".$request['length']."   ";

	$stmt = $dbo->prepare($sqlAll);
	// Execute the query
	$stmt->execute([$admin,$emptyValues,$adminLive,$adminType,$customusDomestic,$adminChina,$adminIndia,$adminCustom,$customusaustinCulver,$customuschinaTokyo,$customcorkuaeBayarea,$customchinashanghaiBeijing,$adminselfMoves,$adminmilanVienna,$custombayareaSeattle,$custombayareaCulver,$customculverSingapore,$customcanada]);

	$totalData = $stmt->fetchAll(PDO::FETCH_ASSOC);


	$newData = array();
	// Convert all the data to UTF-8 unicode format.
	foreach($totalData as $item) {
		$nestedData=array(); 

		$nestedData[] = mb_convert_encoding($item['name'], 'UTF-8', 'UTF-8');
		$nestedData[] = mb_convert_encoding($item['email'], 'UTF-8', 'UTF-8');
		$nestedData[] = mb_convert_encoding($item['usergroup'], 'UTF-8', 'UTF-8');
		$nestedData[] = mb_convert_encoding($item['user'], 'UTF-8', 'UTF-8');
		$nestedData[] = mb_convert_encoding($item['DateAdded'], 'UTF-8', 'UTF-8');
		$nestedData[] = '<i class="fas fa-edit" data-toggle="modal" data-target="#editModal" id="'.$item['mem_id'].'"></i> <i class="fas fa-trash" id="'.$item['mem_id'].'"></i>';
	
		$newData[] = $nestedData;
	}


	$json_data = array(
		"draw"            => intval( $request['draw']), 
		"recordsTotal"    => intval( $rowCount ),  
		"recordsFiltered" => intval( $totalFiltered ),
		"data"            => $newData  
	);

	echo json_encode($json_data);
  
  // This is fine but what happens when I need to make another ajax call to this file? It'll read all the contents of this script how can I make it to where it reads only certain code within the same file?

【问题讨论】:

    标签: javascript php ajax pdo


    【解决方案1】:

    您可以使用 if 块条件来执行特定的 ajax 调用假设您想从第一个 ajax 调用执行第一个 if 块,那么您必须使用 ajax 传递参数,您的第一个 if 块条件是 true 和相同的方式用于所有 ajax 调用。

    PHP 代码

     <?php 
         if($_POST['DATA']=='FIRST'){
           all statements are here.
          }else if($_POST['DATA']=='SECOND'){
           all statements of second block is here.
          }else if($_POST['DATA']=='THIRD'){
            all statements of the third block are here.
          }   so on 
      ?>
    

    AJAX 调用

      // First AJAX CALL for FIRST IF BLOCK
      $.ajax({
            url: 'please give php file url',
            data:{ DATA: 'FIRST' },
            success: function(){
                console.log('works');
            }
        });
      //  Second AJAX CALL for SECOND IF BLOCK
        $.ajax({
            url: 'please give php file url',
            data:{ DATA: 'SECOND' },
            success: function(){
                console.log('works');
            }
        });
      // so on 
    

    我认为,我在正确的轨道上 :)

    【讨论】:

    • 这实际上是我一直在寻找的,但是,我认为@Geomorillo 响应更建议,我认为最好将不同文件中的操作多样化,而不是将所有操作都放在一个文件中。不过感谢您的回复。
    【解决方案2】:

    但这不会被认为是糟糕的架构吗?不,按照你的方式去做会是糟糕的架构。不同文件中的单独操作(delete.php、update.php、create.php)会更好、更易于维护,但我在谈论 php 部分,是的,您可以在同一个 javascript 上对这些文件进行所有调用 例如:

    //crud.js
    
    $("#delete_button").on('click', function(e){
            $.ajax({
                url: '../delete.php',
                success: function(){
                    console.log('deleted');
                }
            })
        });
    
    $("#update_button").on('click', function(e){
            $.ajax({
                url: '../update.php',
                success: function(){
                    console.log('updated');
                }
            })
        });
    $("#create_button").on('click', function(e){
            $.ajax({
                url: '../create.php',
                success: function(){
                    console.log('created');
                }
            })
        });
    

    【讨论】:

    • 好的,谢谢您的建议,我会在未来考虑到这一点。
    猜你喜欢
    • 1970-01-01
    • 2014-08-03
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-13
    • 1970-01-01
    • 2012-10-16
    • 2013-10-17
    相关资源
    最近更新 更多