如何修改字符串避免AJAX POST请求发送至服务器时出错?
Fixing JSON Format Errors When Your Data Contains Double Quotes in AJAX POST Requests
You’re hitting a super common issue here—manually building JSON strings is risky because special characters like double quotes break the JSON syntax (that extra quote in some"text closes the string prematurely, making the whole payload invalid).
Instead of cobbling together the JSON by hand, create a plain JavaScript object first, then use JSON.stringify() to convert it into a properly escaped, valid JSON string. This method automatically handles all special characters for you.
Here’s your corrected code:
$.ajax({ type: "POST", url: "../someService", contentType: "application/json; charset=utf-8", dataType: "json", // Use a JS object, then let JSON.stringify handle escaping data: JSON.stringify({ prefixText: 'some"text', count: 10 }), success: function(data) { response(data.d); }, error: function(error) { alert("error"); } });
Why this works:
JSON.stringify()will automatically escape the double quote insome"texttosome\"textin the final JSON payload. This keeps the JSON structure intact so your WebService can parse it correctly.- Manual JSON string construction is error-prone, especially when dealing with dynamic data or user input. Using a native object +
JSON.stringify()is the standard, reliable way to send JSON via AJAX.
内容的提问来源于stack exchange,提问作者Michael




