jQuery Ajax调用php函数会破坏JSON数据

时间:2013-10-08 13:26:47

标签: javascript php jquery ajax utf-8

我发送一封带有jQuery ajax调用的电子邮件到php函数。格式为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-code:

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."!");
}
?>

2 个答案:

答案 0 :(得分:0)

我的猜测是你要使用以下内容:

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."!");
}
?>

答案 1 :(得分:0)

来自php-documentation:

“文本行的最大总长度,包括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."!");
}
?>