我正在通过检索JSON数据将一些Google图书信息发送到我的数据库。我的代码如下

$.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中有多个类别,则单词'Array'为
发送到我的数据库。
如果JSON中没有作者,则我的脚本无法运行,我
在控制台中收到以下错误;

未捕获的TypeError:无法读取未定义的属性“ 0”


对于JS和PHP来说还很新,因此欢迎您提出任何建议和方向。

最佳答案

在使用数组下标entry.volumeInfo.authors之前,您需要检查[0]是否存在。

'author' : (entry.volumeInfo.authors ? entry.volumeInfo.authors[0] : 'not available'),


如果类别与作者相似,则可以对类别进行类似的操作:

'category' : (entry.volumeInfo.categories ? entry.volumeInfo.categories[0] : 'not available'),


上面,我使用ternary operator添加条件内联。

关于php - Ajax和Google图书,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27358559/

10-08 21:58
查看更多