我通过检索JSON数据将一些Google Book信息发送到我的数据库。我的代码如下
$.ajax({
type: 'POST',
url: 'addIsbnScript.php',
data: {
'isbn' : isbn,
'title' : entry.volumeInfo.title,
'subtitle' : entry.volumeInfo.subtitle||'not available',
'author' : entry.volumeInfo.authors[0]||'not available',
'category' : entry.volumeInfo.categories ||'not available',
'description' : entry.volumeInfo.description ||'not available'
},
});
addIsbnScript.php
$title = $_POST['title'];
$category = $_POST['category'];
$author = $_POST['author'];
$isbn = $_POST['isbn'];
$subtitle = $_POST['subtitle'];
$description = $_POST['description'];
$query = $conn->prepare("INSERT INTO `book` (title,category,author,isbn,subtitle,description) VALUES (?,?,?,?,?,?)");
$query->bind_param('ssssss',
$title,
$category,
$author,
$isbn,
$subtitle,
$description
);
$query->execute();
大多数情况下,所有数据都成功发送,但是我注意到两件事;
如果 JSON 中有多个类别,则单词"数组"为发送到我的数据库。
如果 JSON 中没有作者,我的脚本不会运行,我在控制台中收到以下错误;
未捕获的类型错误:无法读取未定义的属性"0"
对JS和PHP非常陌生,所以欢迎任何建议和指导。
您需要
在使用数组下标[0]
之前检查entry.volumeInfo.authors
是否存在。
'author' : (entry.volumeInfo.authors ? entry.volumeInfo.authors[0] : 'not available'),
如果类别与作者的字段类似,则可以对类别执行类似的操作:
'category' : (entry.volumeInfo.categories ? entry.volumeInfo.categories[0] : 'not available'),
上面,我正在使用三元运算符来添加条件内联。