0
我想從PostgreSQL數據庫(字段類型是文本)帶有ajax到我的網頁中的一組文本。我遇到的問題是換行符,它在數據庫中沒有換行符時運行良好,但是當我在數據庫中的文本中使用新行時,json不會向我提供它存儲的數據。在json對象中接收換行
function selectCalendarEvents(user_id, event_datestart, event_datestop, callback) {
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
if(request.responseText.substr(0, 6) == "error ")
alert(errorName[request.responseText.substr(6)]);
else {
jsonCalendarEvents = $.parseJSON(request.responseText);
selectEvents(user_id, event_datestart, event_datestop, callback);
}
}
}
request.open("GET", "php/calendar.php?action=selectCalendarEvents&user_id=" + user_id + "&event_datestart=" + event_datestart + "&event_datestop=" + event_datestop, true);
request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
request.send();
}
這是我的JavaScript函數,它要求數據集
if($action == "selectCalendarEvents") {
$user_id = $_GET["user_id"];
$event_datestart = "'" . $_GET["event_datestart"] . "'";
$event_datestop = "'" . $_GET["event_datestop"] . "'";
require_once("connect.php");
$query = "SELECT event_id, event_name, event_datestart, event_datestop, event_timestart, event_timestop, calendar_events.calendar_group, calendar_color, event_info FROM calendar_events LEFT JOIN calendar_calendars ON calendar_events.calendar_group = calendar_calendars.calendar_group WHERE user_id = " . $user_id . " AND calendar_show = true AND event_datestart <= ". $event_datestop . " AND event_datestop >= " . $event_datestart;
$result = pg_query($connect, $query);
if(!$result)
die("error 1"); // query error
$comma = '';
$json = '{"events":[';
while ($row = pg_fetch_row($result)) {
$json .= $comma . '{';
$json .= '"event_id":"' . $row[0] . '",';
$json .= '"event_name":"' . $row[1] . '",';
$json .= '"event_datestart":"' . $row[2] . '",';
$json .= '"event_datestop":"' . $row[3] . '",';
$json .= '"event_timestart":"' . $row[4] . '",';
$json .= '"event_timestop":"' . $row[5] . '",';
$json .= '"calendar_group":"' . $row[6] . '",';
$json .= '"calendar_color":"' . $row[7] . '",';
$json .= '"event_info":"' . $row[8] . '"';
$json .= '}';
$comma = ',';
}
$json .= ']}';
echo $json;
}
這是我的PHP返回的數據集。如果行[8] aka event_info存儲帶有換行符的文本..當我嘗試用事件填充日曆時,它似乎json不存儲任何數據或smt那樣。
逃生JavaScript中的新行: http://stackoverflow.com/questions/4253367/how-to-escape -a-json-string-containing-newline-characters-using-javascript – bArmageddon 2012-03-29 09:30:12
你也可以閱讀關於替換json [line break到html換行符]的教程(http://www.lampcoder.com/how-to-parse -line-斷裂-使用-jQuery的後方法和 - JSON /) – 2012-08-16 12:05:22