jQuery ajax/post 响应编码

4

我是一名有用的助手,可以为您翻译文本。

我遇到了一个关于通过ajax加载json编码信息的问题。

以下是PHP代码(test.php):

<?php
  $val1 = 'Productmanager m / f';
  $val2 = 'test';
  $arr = array('first' => $val1, 'second' => $val2);
  echo json_encode($arr);
?>

在html文件中的JavaScript代码:

$(document).ready(function() {
  $.post("test.php", function(data){
    var response = $.parseJSON(data);
    console.log(response.first);
    console.log(response.second);
  }
});

控制台上的结果如下:

Productmanager&#x20;m&#x20;&#x2f;&#x20;f

并且

test

这两个文件都是UTF-8编码的。

我真的不知道为什么以及如何将其转换回可读字符串。你可能有一个想法,这是怎么发生的?

我第一次尝试没有找到合适的解决方案,只能使用搜索和替换的方法。


更新后正常运行! - Khazl
3个回答

3

添加正确的 PHP 头并解码字符串:

<?php
  header("Content-type: application/json");
  $val1 = "Productmanager m / f";
  $val2 = "test";
  $arr = array("first" => $val1, "second" => $val2);
  echo json_encode($arr);
?>

<script>

    $(document).ready(function() {
      $.post("test.php", function(data){
        var response = $.parseJSON(data);
        console.log(htmlDecode(response.first));
        console.log(response.second);
      }
    });

function htmlEncode(value){
  return $('<div/>').text(value).html();
}

function htmlDecode(value){
  return $('<div/>').html(value).text();
}

</script>

好的,那我需要删除 "var response = $.parseJSON(data);",结果是一样的。 - Khazl

0

你能试试这个吗?

$(document).ready(function() {
    $.ajax({
        type: "POST",
        url: "test.php",
        contentType: "application/x-www-form-urlencoded;charset=UTF-8",
        dataType: 'json',
        success: function(data) {
            var response = $.parseJSON(data);
                console.log(response.first);
                console.log(response.second);
        }
    });
});

您可以通过使用“contentType”为ajax请求设置字符编码。

在您的php端,您的代码必须如下:

<?php
  $val1 = 'Productmanager m / f';
  $val2 = 'test';
  $arr = array('first' => $val1, 'second' => $val2);
  echo json_encode($arr, JSON_UNESCAPED_UNICODE);
?>

重要提示:JSON_UNESCAPED_UNICODE 只适用于 PHP 5.4.0 以上版本!!

我尝试了这个,但必须删除$ .parseJSON,因为响应已经被解析。结果是一样的。 - Khazl
我的网站空间使用的是 PHP 5.3.10。 - Khazl

0

你可以尝试将此代码应用于你的test.php文件中。

<?php
  $val1 = 'Productmanager m / f';
  $val2 = 'test';
  $arr = array('first' => $val1, 'second' => $val2);
  echo json_encode($arr, JSON_UNESCAPED_UNICODE);
?>

以空响应结束 :-/ - Khazl
你需要 PHP 版本 5.4.0 才能使用 JSON_UNESCAPED_UNICODE 选项,所以你可以尝试运行你的 test.php 文件并查看它的输出。 - Peeyush

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接