【问题标题】:jQuery Ajax call to a php function corrupts JSON data对 php 函数的 jQuery Ajax 调用损坏了 JSON 数据
【发布时间】:2013-10-15 10:50:06
【问题描述】:

我向 php 函数发送了一封带有 jQ​​uery ajax 调用的电子邮件。格式为 UTF-8,电子邮件发送正常。但是在服务器函数接收到的数据($message)中,每隔大约 1000 到 1200 个字符就会增加一个新行。

示例:(“und si”和“e sich”之间换行):

{
                "content": "Vielen war es einfach zu viel Aufwand, zu verschlüsseln. Oder sie waren einfach träge. Sie wollten nicht verschlüsseln, weil es Zeit kostete und si

e sich in etwas Neues hineindenken mussten.",

javascript代码:

var factString = JSON.stringify(fact);
$.ajax({
    type: "POST",
    url: "email.php",
    data: "json="+factString+"&thought="+currentThought,
    success: function(r){
        $('#send_thought .buttontext').html("GEDANKE WEGGESCHICKT!");
    }
});

php:

<?php

ini_set( 'default_charset', 'UTF-8' );
mb_internal_encoding('UTF-8');

if($_POST){
    $thought = $_POST['thought'];
    $message = utf8_decode($_POST['json']);

//send email
    mail("michael@primaerarbeit.de", "Gedanke ".$thought." von CP11", $message);

    print("Sent thought ".$thought."!");
}
?>

【问题讨论】:

  • 为什么没有 $message = utf8_decode(json_decode($_POST['json']));在你的代码中?
  • 它是一个字符串。为什么我要把它解码为 json?我试过了,它返回一个错误...
  • 为什么要发布为 JSON 字符串?为什么data 是字符串而不是对象?
  • “只有大约每 1000 到 1200 个字符,电子邮件文本中才会有一个额外的新行。” – 在您的服务器端脚本传递的数据中,或在电子邮件中收到了吗?
  • 在服务器端过去的数据中...

标签: javascript php jquery ajax utf-8


【解决方案1】:

我猜你想使用以下内容:

JS:

$.ajax({
    type: "POST",
    url: "email.php",
    data: {
        fact: fact,
        thought: currentThought
    },
    success: function(r){
        $('#send_thought .buttontext').html("GEDANKE WEGGESCHICKT!");
    }
});

PHP:

<?php

ini_set( 'default_charset', 'UTF-8' );
mb_internal_encoding('UTF-8');

if($_POST){
    $thought = $_POST['thought'];
    $message = utf8_decode($_POST['fact']);

    //send email
    mail("michael@primaerarbeit.de", "Gedanke ".$thought." von CP11", $message);

    print("Sent thought ".$thought."!");
}
?>

【讨论】:

  • 我对参数进行了更改,它也可以工作并且更好。但它仍然每 1000 到 12oo 个字符插入新行。
  • 你在什么阶段看到了新的线路?已经在$_POST?在utf8_decode 之后或在您收到的电子邮件中?
【解决方案2】:

来自 php 文档:

"包含 1000 个字符的文本行的最大总长度" (RFC 821)

我的解决方案是使用“wordwrap”:

<?php

ini_set( 'default_charset', 'UTF-8' );
mb_internal_encoding('UTF-8');

if($_POST){
    $thought = $_POST['thought'];
    $email = $_POST['email'];
    $message = utf8_decode($_POST['json']);

    $message = wordwrap($message);
    $message = str_replace("\n", "\r\n", $message);

    mail("michael@primaerarbeit.de, ".$email, "Gedanke ".$thought." von ".$email, $message);

    print("Sent thought ".$message."!");
}
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 2011-01-17
    • 1970-01-01
    相关资源
    最近更新 更多