gpt4 book ai didi

javascript - 如何使用 Ajax 表单将语言设置为中文提交到不同的 PHP 文件?

转载 作者:行者123 更新时间:2023-12-02 17:04:12 25 4
gpt4 key购买 nike

我正在开发一个中文项目(gb2312)。我们有一个表单,使用 Ajax 将客户输入数据从文件 1 提交到 php 文件 2。两个文件显示中文没有问题。但当相同的数据从文件1提交到文件2时,它变成了完全错误的字符。例如:

文件1

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>

<div id="msg">0</div>

<form id="add-form" action="file2.php" method="POST">
<input type=text name='content' value='试试这个' >
<input type="button" id="add-post" value="Run Code" />
</form>


<script>
$(document).ready(function()
{

$("#add-post").click(function()
{
$("#add-form").submit(function(e)
{
$("#msg").html("<img src='/image/progress_bar.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url: formURL,
type: "POST",
data : postData,
contentType: "application/x-www-form-urlencoded;charset=gb2312",
success:function(data, textStatus, jqXHR)
{
$("#msg").html('<pre>'+data+'</pre>');
},
});
e.preventDefault(); //STOP default action
e.unbind();
});

$("#add-form").submit(); //SUBMIT FORM
});
});
</script>


</body>
</html>

文件2

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<?php
echo $_POST['content'];
?>
</body>
</html>

两个文件都可以正常显示汉字。但是当从文件1向文件2提交中文内容时,内容变成乱码,看起来不是正确的字符。我认为问题应该出在 Ajax 提交脚本中的某个地方,但不知道如何修复它。

你能帮我一下吗?预先感谢您。

最佳答案

是的,问题肯定出在Ajax请求上。如果你看jQuery documentation对于 contentType 属性,您将看到以下注释:

The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.

在为浏览器呈现页面时,您可以返回 GB2312 字符,但看起来 Ajax 请求将始终以 UTF-8 发送。因此,您需要让 PHP 脚本接受 UTF-8,才能正确解析数据。我建议从 Ajax 请求中删除 contentType header 。

当你的 PHP 收到 UTF8 编码的字符串后,你可以使用 iconv 将其转换回 GB2312。功能:

$chinese_content = iconv('UTF-8', 'GB2312', $_POST['content']);

关于javascript - 如何使用 Ajax 表单将语言设置为中文提交到不同的 PHP 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25410688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com