weixin_33726943 2014-12-08 12:58 采纳率: 0%
浏览 1

Ajax和Google图书

I am sending some Google Book info to my db by retrieving JSON data. My code is below

$.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();

Most of the time all of the data sends successfully, however I have noticed two things;

  • If there is more than one category in the JSON, the word 'Array' is sent to my db.

  • If there is no author present in the JSON my script doesn't run and I receive the following error in the console;

    Uncaught TypeError: Cannot read property '0' of undefined

Very new to JS and PHP so any advice and direction is welcome.

  • 写回答

1条回答 默认 最新

  • weixin_33704591 2014-12-08 15:53
    关注

    You'll want to check entry.volumeInfo.authors exists before using the array subscript [0].

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

    If categories is a similar field to authors, you can do something similar for categories:

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

    Above, I'm using a ternary operator to add a conditional inline.

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog