2012-04-22 114 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