如何在AJAX中传递无键名的单个字符串?
Hey there! Let's break down why your code isn't running and confirm that sending a raw string as your request body is totally feasible—you just need to tweak a few things to match the content type you're using.
What's Going Wrong?
You set contentType: "application/json; charset=utf-8", which tells the server to expect JSON-formatted data. But the string "HATETH" you're passing isn't valid JSON on its own:
- JSON requires strings to be wrapped in double quotes (single quotes won't work here)
- When sending a raw string as the full JSON payload, you need to properly serialize it into a valid JSON value.
jQuery doesn't auto-serialize strings to JSON when you set contentType: "application/json"—it expects either a pre-serialized JSON string or an object (which it will serialize for you).
Fix 1: Send Valid JSON (Best for JSON-Expecting APIs)
Use JSON.stringify() to convert your string into a properly formatted JSON payload. This wraps your string in double quotes and ensures the server recognizes it as valid JSON:
$.ajax({ type: "POST", url: 'MY_API_URL', data: JSON.stringify("HATETH"), // Serialize the string to valid JSON contentType: "application/json; charset=utf-8", dataType: "json", success: function (r) { console.log(r); }, error: function(xhr, status, error) { // Add error handling to debug issues easily console.error("Request failed:", error); console.log("Server response:", xhr.responseText); } });
Fix 2: Send Plain Text (If Backend Supports It)
If your server is configured to accept raw plain text instead of JSON, switch the contentType to "text/plain". This lets you send the string directly without any serialization:
$.ajax({ type: "POST", url: 'MY_API_URL', data: "HATETH", contentType: "text/plain; charset=utf-8", dataType: "json", // Keep this if the server returns JSON; change to "text" if not success: function (r) { console.log(r); }, error: function(xhr, status, error) { console.error("Request failed:", error); } });
Quick Tips
- Always double-check your backend's docs to confirm what request format it expects (JSON vs plain text).
- The
errorcallback is a lifesaver for debugging—it'll show you exactly why the request is failing (like invalid JSON errors from the server).
内容的提问来源于stack exchange,提问作者Wos

