2012-04-22 116 views
4

我有一个json编码信息通过ajax加载的问题。jQuery ajax/post响应编码

的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编码。

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

我已经找到没有合适的解决方案了,先去搜索&替换方法。

+1

我的回答已经更新。 – iambriansreed 2012-04-22 16:56:34

+0

更新后正常工作! – Khazl 2012-04-22 17:03:28

回答

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> 
+0

好吧,那么我必须删除“var response = $ .parseJSON(data);”并且结果是相同的 – Khazl 2012-04-22 16:16:31

+0

O.K.更新后它可以正常工作:-)非常感谢! – Khazl 2012-04-22 17:02:43

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”

在你的php侧设置Ajax请求的字符编码,代码必须像;

<?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!

+0

我试试这个,但必须删除$ .parseJSON,因为响应已经被解析。结果是一样的。 – Khazl 2012-04-22 16:21:35

+0

什么是您的PHP版本? – 2012-04-22 16:34:13

+0

我的网站空间运行PHP 5.3.10 – Khazl 2012-04-22 16:40:59

0

你可以试试这个你test.php

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

结束于一个空的回应: -/ – Khazl 2012-04-22 16:13:59

+0

你应该有PHP版本5.4.0与该JSON_UNESCAPED_UNICODE选项一起工作,所以你可以试试运行你的test.php文件,看看它有什么输出是给 – Peeyush 2012-04-22 16:19:48

+0

抱歉,但即时通讯授权更新PHP版本。 – Khazl 2012-04-22 17:16:09