【发布时间】:2015-10-23 00:02:18
【问题描述】:
我从 mysql 获取一些数据并使用 json 将其发送到服务器。但是将数据作为数组发送会在我的结果中添加反斜杠。
PHP:
$result = mysql_query("SELECT location_name, phone_number FROM location WHERE email_id = 'abc@gmail.com'");
$result_array = array();
while($row = mysql_fetch_assoc($result))
{
$result_array[] = $row;
}
echo json_encode($result_array);
JS:
$$.ajax({
url: 'http://www.abc.co/SupportData/get_business_locations.php',
type: "POST",
data: {
email: window.localStorage["email"]
},
dataType: "JSON",
success: function (jsonStr) {
console.log(JSON.stringify(jsonStr));
}
});
输出:
[{\"location_name\":\"Bandra\",\"phone_number\":\"\"},{\"location_name\":\"Dadar\",\"phone_number\":\"\"},{\"location_name\":\"ee\",\"phone_number\":\"\"},{\"location_name\":\"ttttt\",\"phone_number\":\"\"}]""
【问题讨论】:
-
使用
json_encode($result_array, JSON_UNESCAPED_SLASHES);删除反斜杠 -
我刚刚从 JS 中删除了
JSON.stringify,它运行良好。还是不知道为什么? -
JSON.stringify 将对象转换为 JSON 文本并将该 JSON 文本存储在字符串中。可选。在返回值 JSON 文本中添加缩进、空格和换行符,使其更易于阅读。
-
@Nehil,请参阅下面的答案。这是因为 JSON.stringify 有效地 DOUBLE json_encodes 您的数据,一次在 PHP 中,一次在 JS 中。如果你想在你的 JS 脚本中添加一个 JS 对象,请使用 JSON.parse,它会将 JSON 字符串解析为一个 JS 对象。
标签: php jquery mysql arrays json