You could use
echo json_encode( array("text" => $text, "variable2" => $value2) );
to make sure it's valid JSON and escaped correctly, that way it wouldn't break on quotes, spaces etc.
题
So in my website I'm using a TinyMCE window. In the current way PHP fetches an entry from the database, decodes this as JSON. The in-page javascript then parses this. However, if there's a style='color:#fff'
or anything similar in there, the javascript can't parse the JSON. Also, spaces or exclamation mark can break it. I don't want to use something so fragile. Is there any other way to solve this?
Javascript
$.ajax({
type: "POST",
url: "Including/php/fetcher.php",
data: { identifier: identifier, page: page }
}).done(function( msg ) {
var data = $.parseJSON(msg);
var text = data["text"];
tinyMCE.activeEditor.setContent(texten);
};
fetcher.php
$conn = mysql_connect($row['ipdb'],$row['usernamedb'], $row['wwdb']) or die("err");
$db = mysql_select_db($row['usernamedb']) or die("err");
$identifier = $_POST['identifier'];
$page = $_POST['page'];
$qry = "SELECT text FROM ".$page." WHERE identifier='$identifier'";
$result = mysql_query($qry) or die("An error occurred ".mysql_error());
$obj = mysql_fetch_object($result);
$text = $obj->text;
echo '{ "text" : "' . $text . '"}';
解决方案
You could use
echo json_encode( array("text" => $text, "variable2" => $value2) );
to make sure it's valid JSON and escaped correctly, that way it wouldn't break on quotes, spaces etc.