我正在尝试通过JSON将PDO关联数组传递给某些javascript代码。我已经验证了php代码可以生成记录集,但是我在结果上使用jquery的$ .parseJSON会出错。返回结构中的前三个值都是整数,解析器正确理解它们。一旦它达到第一个字符串值,所有赌注都会关闭。报告的错误是意外的令牌,数字等,具体取决于正在解析的非数字字段。日期,字符串等都属于同一个问题。
我在StackOverflow上查看了其他线程,发现它看起来很相似,但没有什么是完全相同的问题。
这是返回的JSON数组的示例(来自php的json_encode,为了简洁而剪切):
{ "idInventory":"451", "idAssociationGroup":"78","idMasterComponent":"601", "QuantityDescription":"Approx 4,450 GSY", "Quantity":null, "Location":"Hallways, Lobby, Locker Room, Library, and Lounge" }
前三个元素都通过下面的代码正确发布,但QuantityDescription(以及后面的任何内容)都失败了。
这是javascript代码的一部分,它应该解析结果并将其放在屏幕上:
$.getJSON(
path + "/Inventory/getComponent.php",
{idComponent: idComponent},
function (data) {
document.getElementById('idInventory').innerHTML = $.parseJSON(data.idInventory);
document.getElementById('idAssociationGroup').innerHTML = $.parseJSON(data.idAssociationGroup);
document.getElementById('idComponentsUsed').innerHTML = $.parseJSON(data.idMasterComponent);
document.getElementById('QuantityDescription').innerHTML = $.parseJSON(data.QuantityDescription);
/* more fields go here, but I've snipped them for brevity, since *
* the error is already exposed */
}
);
答案 0 :(得分:1)
取消对$.parseJSON
的来电。整个响应是JSON,$.getJSON
会自动为您解析。各个字段只是普通字符串,它们不是JSON。
所以第一项任务应该是:
document.getElementById('idInventory').innerHTML = data.idInventory;
和所有其他作业类似。