AJAX — 不使用 URLencoding 发送 JSON
AJAX — sending JSON without URLencoding
OBJECTIVE & 背景
比较两个文本示例。这些文本样本是产品的描述。示例 1 是从表单中的文本区域抓取的。示例 1 通过 AJAX 发送到另一个文件以与从数据库中获取的示例 2 进行比较。
我正在尝试作为 JSON 对象发送,因为我认为这将允许我在普通 POST / GET 请求中发送 URL 编码数据。
问题
当我在 JSON 对象中通过 AJAX 发送样本 1 时,它使用 +
进行 URL 编码以用于空格等...我需要发送文本 "as is" 这样就可以进行比较了。 URL 解码将不起作用,因为可能确实存在 +
和属于真实示例 1 的其他字符。
问题
如何在不对数据进行 URL 编码的情况下发送示例 1?
代码
// we need the product id and description
var pid = $("input[name='pid']").val();
var descr = $("textarea[name='descr']").val();
// put in a json object so we can see the real data
var $obj = {
"pid": pid,
"descr": descr // Sample 1
}
// make the call and return the promise
return $.ajax({
type: 'POST',
url: 'request_file.php',
dataType: "json",
data: $obj
});
来自 jquery docs 对于 $.ajax
API,
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
所以默认情况下,它将仅作为 url 编码发送。通过设置正确的参数,按如下方式更新 AJAX 调用。
return $.ajax({
type: 'POST',
contentType :'application/json',
url: 'request_file.php',
dataType: "json",
data: $obj
});
contentType
参数通常采用 MIME 类型作为值。在发送请求时为用例设置正确的 MIME 类型,以及在后端使用 same MIME 类型从请求中读取数据总是如此。
您可以参考 here for various MIME types 可用的。
OBJECTIVE & 背景
比较两个文本示例。这些文本样本是产品的描述。示例 1 是从表单中的文本区域抓取的。示例 1 通过 AJAX 发送到另一个文件以与从数据库中获取的示例 2 进行比较。
我正在尝试作为 JSON 对象发送,因为我认为这将允许我在普通 POST / GET 请求中发送 URL 编码数据。
问题
当我在 JSON 对象中通过 AJAX 发送样本 1 时,它使用 +
进行 URL 编码以用于空格等...我需要发送文本 "as is" 这样就可以进行比较了。 URL 解码将不起作用,因为可能确实存在 +
和属于真实示例 1 的其他字符。
问题
如何在不对数据进行 URL 编码的情况下发送示例 1?
代码
// we need the product id and description
var pid = $("input[name='pid']").val();
var descr = $("textarea[name='descr']").val();
// put in a json object so we can see the real data
var $obj = {
"pid": pid,
"descr": descr // Sample 1
}
// make the call and return the promise
return $.ajax({
type: 'POST',
url: 'request_file.php',
dataType: "json",
data: $obj
});
来自 jquery docs 对于 $.ajax
API,
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
所以默认情况下,它将仅作为 url 编码发送。通过设置正确的参数,按如下方式更新 AJAX 调用。
return $.ajax({
type: 'POST',
contentType :'application/json',
url: 'request_file.php',
dataType: "json",
data: $obj
});
contentType
参数通常采用 MIME 类型作为值。在发送请求时为用例设置正确的 MIME 类型,以及在后端使用 same MIME 类型从请求中读取数据总是如此。
您可以参考 here for various MIME types 可用的。