我试图在服务器上保存一些数据,但发现一些编码问题。
这就是我将对象发送到 PHP 的方式(效果很好,但我认为 contentType 实际上并没有做任何事情):
$.post(
'myfile.php',
{
contentType: "application/x-www-form-urlencoded;charset=utf-8",
data : myData
},
function (data, textStatus, jqXHR){
//some code here
}
);
然后在 PHP (myfile.php) 中:
<?php
header('Content-Type: text/html; charset=utf-8');
$file = 'data/theData.txt'; //the file to edit
$current = file_get_contents($file); // Open the file to get existing content
$a2 = json_decode( $current, true );
$data = $_POST['data']; //the data from the webpage
$res = array_merge_recursive( $data, $a2 );
$resJson = json_encode( $res );
// Write the contents back to the file
file_put_contents($file, $resJson);
?>
如您所见,我正在获取文件的原始内容并解码 json。然后我将结果与从网页发送的数据合并,然后在 json 中重新编码并将内容放回原处。
这一切都按预期工作。然而,在我的 Jquery 中的某一时刻,发送的数据包含各种各样的符号,例如“/ö é ł Ż ę”
保存文件时,每个“/”前面都有一个转义字符“\”,同样,“é”例如是“\u00e9”
我该如何覆盖这个?我应该尝试在 PHP 中正确转换它,还是在我有 $.get('data/theData.txt' 之后在 JQuery 中转换回正确格式?
非常感谢您对这个问题的任何了解!请原谅可怜的变量名。