0

我正在尝试从数据库中获取带有特殊字符(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));
?>
4

2 回答 2

0

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

utf8_encode($variable);

或尝试array_map();对数组进行编码;

$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();

You may need to try one or the other or even both. You also want to confirm your DB is able to store special characters, if the DB is not storing the special chars then there is no way your application will be able to get them to encode them.

于 2012-09-11T16:22:44.020 回答
0

Adding in the line $mysql->query("SET CHARACTER SET 'utf8'"); inside loadTextBox.php after connecting to the DB and before the SQL query fixed it.

于 2012-09-16T04:59:29.823 回答