jQuery/PHP 使用 JSON 发布表单 - 如何正确处理其中包含换行符的服务器响应?
发布工作非常顺利,并且愉快地阅读响应,除非其中一个数据元素中有换行符 (\n)。经过几个小时的谷歌搜索,我现在完全感到困惑和困惑。我错过了什么,或者做错了什么才能接收包含换行符的数据元素?在这种特殊情况下,我将把它显示给用户,所以
标签很好,但我最初希望它在 a 中进行编辑,并且返回的任何换行符都会给我错误。
.click(function() {
var $form = $("#product_data_form");
var dataString = $form.serialize()
$.ajax({
type: "POST",
url: "utility02a.php",
data: dataString,
dataType: "json",
success: function(server_response)
{
$("div#my_results").append(server_response.MyTextWithNewLines);
}
});
然后,在服务器上,在 PHP 中(除非响应中存在 \n,否则这会按预期工作
echo '{';
echo '"status":"'.$status.'",';
echo '"MyTextWithNewLines":"'.json_encode($sometext).'"';
echo '}';
,我确定这是沿线某个地方的编码问题,但我的眼睛在旋转,试图了解如何编码、在何处编码以及简而言之
,返回的数据应该能够在文本区域中进行编辑,并在用户的输入区域中正确表示新行。
Have posting working wonderfully, and reading the response happily EXCEPT when one of the data elements has new lines in it (\n). Hours and hours of googling, and I'm completely confused and baffled at this point. What am I missing, or doing wrong with this to be able to receive a data element that has newlines in it? In this particular case I'm going to display it to the user, so
tags are fine, but I'd originally wanted it to be in a for editing and any newlines returned give me errors.
.click(function() {
var $form = $("#product_data_form");
var dataString = $form.serialize()
$.ajax({
type: "POST",
url: "utility02a.php",
data: dataString,
dataType: "json",
success: function(server_response)
{
$("div#my_results").append(server_response.MyTextWithNewLines);
}
});
Then, on the server, in PHP (and this works as expected unless there are \n's in the response
echo '{';
echo '"status":"'.$status.'",';
echo '"MyTextWithNewLines":"'.json_encode($sometext).'"';
echo '}';
I'm sure it's an encoding issue somewhere along the line, but my eyes are spinning trying to understand what to encode how, where and when.
In short, the data returned should be able to be in a textarea for editing, with the new lines properly represented in the input area for the user.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能想使用 json_encode 来代替,因为我将它与换行符一起使用没有问题。构建要编码的数据的关联数组。一旦在客户端解码,数组的键将是 json 对象成员:
这应该可以为您提供!
You may want to use
json_encode
instead, as I use that with newlines with no issue. Build an associative array of the data you want to encode. The keys of the array will be the json objects members once it's decoded on the client side:That should get it for you!