使用json_encode通过xmlhttp.responseText发送特殊字符(即caron)


Sending special characters (i.e. caron) through xmlhttp.responseText using json_encode

我正试图从数据库中获取带有特殊字符(caron)的数据,并使用json_encode填充文本框,通过xmlhttp.responseText发送。与包含特殊字符(caron)的数据相关联的特定文本框不显示任何内容。其他文本框显示正确的数据。我尝试使用Javascript函数encodeURIComponent,但在文本框中只显示了null。如有任何帮助,我们将不胜感激。

主页代码:

function loadDoc()
{
   var xmlhttp;
   // code for IE7+, Firefox, Chrome, Opera, Safari
   if (window.XMLHttpRequest)
   {
      xmlhttp=new XMLHttpRequest();
   }
   // code for IE6, IE5
   else
   {
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
   }
   xmlhttp.onreadystatechange=function()
   {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
         var a = JSON.parse(xmlhttp.responseText);
         document.getElementById("textbox").value=a.first;
         document.getElementById("textbox2").value=a.second;
         document.getElementById("textbox3").value=a.third;
         document.getElementById("textbox4").value=a.fourth;
         document.getElementById("textbox5").value=a.fifth;
         document.getElementById("textbox6").value=a.sixth;
      }
   }
   xmlhttp.open("GET","loadTextBox.php?id=4",true);
   xmlhttp.send();
}

loadTextBox.php代码:

<?php
header("Content-type: application/json");
---Placeholder for correct DB login info---
$result = $mysql->query(---Placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
   $queryResult[] = $row->colun_one;
}
$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[1];
$textboxValue3 = $queryResult[2];
$textboxValue4 = $queryResult[3];
$textboxValue5 = $queryResult[4];
$textboxValue6 = $queryResult[5];
echo    
json_encode(array('first'=>$textboxValue,'second'=>$textboxValue2,
'third'=>$textboxValue3,'fourth'=>$textboxValue4,'fifth'=>$textboxValue5,
'sixth'=>$textboxValue6));
?>

在发送它们之前使用UTF-8对它们进行编码。

utf8_encode($variable);

或者尝试CCD_ 2对阵列进行编码;

$textboxValue = $queryResult[0];
$textboxValue2 = $queryResult[1];
$textboxValue3 = $queryResult[2];
$textboxValue4 = $queryResult[3];
$textboxValue5 = $queryResult[4];
$textboxValue6 = $queryResult[5];
$arrayToEncode = array('first'=>$textboxValue,'second'=>$textboxValue2,
'third'=>$textboxValue3,'fourth'=>$textboxValue4,'fifth'=>$textboxValue5,
'sixth'=>$textboxValue6);
$encodedArray = array_map('utf8_encode', $arrayToEncode);
echo json_encode($encodedArray);

您可能还需要将xmlhttp.request设置为utf-8以及

xmlhttp.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();

你可能需要尝试其中一种或另一种,甚至两者都尝试。你还想确认你的数据库能够存储特殊字符,如果数据库没有存储特殊字符那么你的应用程序就无法让它们编码。

在行$mysql->query中添加("SET CHARACTER SET'utf8'");在loadTextBox.php中,在连接到DB之后,在SQL查询修复它之前。