如何将查询字符串传递至AJAX请求?附现有代码场景
Hey there! Let's walk through how to take the query string parameters from your URL (website.test/?module=support&item=callScreen&id=10) and pass them into your AJAX call to ticketAutoclose.php. Here are two straightforward, reliable approaches:
Approach 1: Use the data Property (Cleanest & Recommended)
jQuery's $.ajax() has a built-in data option that lets you pass parameters as an object. It automatically handles URL encoding and appends them to the GET request's URL, which avoids messy string concatenation and reduces error risk.
First, extract the parameters from the current URL using the modern URLSearchParams API, then pass them to the AJAX call:
if ('{/literal}{$currentDate}{literal}' < '{/literal}{$ticket.lock_date} {literal}') { $('#status').attr("disabled", true); // Pull query string parameters from the current page's URL const urlParams = new URLSearchParams(window.location.search); const requestParams = { module: urlParams.get('module'), item: urlParams.get('item'), id: urlParams.get('id') }; $.ajax({ type: 'GET', url: '/modules/support/ticketAutoclose.php', data: requestParams, // Automatically appends parameters to the request URL success: function(response) { // Optional: Add logic to handle a successful response (e.g., update UI) console.log('Autoclose request processed:', response); }, error: function(xhr, status, err) { // Optional: Handle errors like network issues or server errors console.error('Error with autoclose request:', err); } }); }
Approach 2: Directly Append the Full Query String
If you want to pass all query parameters from the original URL without filtering, you can append the existing query string directly to the AJAX endpoint. This is a quick one-liner for simple use cases:
if ('{/literal}{$currentDate}{literal}' < '{/literal}{$ticket.lock_date} {literal}') { $('#status').attr("disabled", true); $.ajax({ type: 'GET', // Append the current URL's query string (slice(1) removes the leading "?") url: '/modules/support/ticketAutoclose.php?' + window.location.search.slice(1) }); }
Handling Parameters in ticketAutoclose.php
Once the parameters are sent, retrieve them in your PHP file using the $_GET superglobal. Always validate and sanitize inputs to avoid security risks like SQL injection or invalid data:
<?php require_once('../../config.php'); $login = new Login(); if (!$login->checkLogin()) { echo lang($_SESSION['language_key']); // Replace with your actual language handling logic exit; } // Retrieve and sanitize parameters $module = isset($_GET['module']) ? trim($_GET['module']) : ''; $item = isset($_GET['item']) ? trim($_GET['item']) : ''; $id = isset($_GET['id']) ? intval($_GET['id']) : 0; // Use intval since ID is numeric // Validate required parameters if (empty($module) || empty($item) || $id <= 0) { echo lang('invalid_parameters'); // Adjust to your project's language string exit; } // Now use $module, $item, and $id in your autoclose logic // ... rest of your code ?>
Quick Notes:
- The
URLSearchParamsAPI works in all modern browsers; if you need to support very old browsers, you can fall back to parsingwindow.location.searchmanually with string methods. - Using the
dataproperty is preferred for readability and to avoid issues with special characters (jQuery handles encoding automatically).
内容的提问来源于stack exchange,提问作者Justin Boxem

