You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改字符串避免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 in some"text to some\"text in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:55:43