如何通过AJAX传递隐藏输入框的数据(非表单场景)
data Parameter for Your AJAX Call Hey there! Let's break down how to fill in that data parameter based on your setup—you've got a hidden input #message-ids holding a comma-separated list of message IDs, and you need to send that data via a POST AJAX request. Here are a few practical options depending on what your backend expects:
Option 1: Send the raw comma-separated string
If your backend is set up to handle a single string value (and will split the commas itself), just pass the input's value directly:
$.ajax({ type: 'POST', url: 'messages-get-new.php', data: { messageIds: $('#message-ids').val() }, // Here's the updated data line success: function (data) { console.log('Submission was successful.'); console.log(data); $container.append(data); }, error: function (data) { console.log('An error occurred.'); console.log(data); }, });
Note: Replace messageIds with whatever parameter name your backend is looking for (e.g., if it uses $_POST['message-ids'], use 'message-ids' as the key instead).
Option 2: Send as an array (for backends expecting array input)
If your backend expects an array of IDs (like PHP's $_POST['messageIds'] being an array), split the string into an array first:
$.ajax({ type: 'POST', url: 'messages-get-new.php', data: { messageIds: $('#message-ids').val().split(',') }, // Split the string into an array of IDs success: function (data) { console.log('Submission was successful.'); console.log(data); $container.append(data); }, error: function (data) { console.log('An error occurred.'); console.log(data); }, });
jQuery will automatically format this array into a backend-friendly structure (e.g., messageIds[]=1&messageIds[]=2&...), so your server code can process it as an array directly.
Option 3: Use FormData (scalable for future form additions)
If you might add more form elements later, using FormData is a flexible approach—even though you only have one hidden input now, this works seamlessly for all form data types:
const formData = new FormData(); formData.append('messageIds', $('#message-ids').val()); $.ajax({ type: 'POST', url: 'messages-get-new.php', data: formData, processData: false, // Required for FormData to work correctly contentType: false, // Required for FormData to work correctly success: function (data) { console.log('Submission was successful.'); console.log(data); $container.append(data); }, error: function (data) { console.log('An error occurred.'); console.log(data); }, });
This is especially useful if you plan to add file uploads or additional inputs down the line.
内容的提问来源于stack exchange,提问作者medk

