【发布时间】:2014-11-24 23:40:40
【问题描述】:
我有一个搜索框,用户在其中输入 ISBN 编号,提交时 div 显示来自 Google Books API 的信息。此信息是从标准格式的 JSON 文件中检索的。我可以毫无问题地在 div 中显示标题、副标题、作者和描述。
然后我有一个 “添加到库” 按钮,它应该将所有这些信息发送到数据库,我的问题是所有字段都从 分开发送>作者。不是发送作者姓名,而是将单词 'Array' 发送到数据库。
我可以让作者姓名发送的唯一方法是将 [0] 添加到我的 Ajax 数据对象的末尾,但是这只会发送第一作者的姓名(如果有 3 个作者,则将省略两个)。
更新 - 它似乎与 JSON 相关,如果我将我的 Ajax 数据更改为“作者”、“行业标识符”或“类别”以外的任何内容,它就可以工作。那是因为它们包含一个列表而不是单个字符串吗?
JS
$(document).ready(function() {
$('#submit').click(function(ev) {
ev.preventDefault();
var isbn = $('#isbn_search').val(); //get isbn direct from input, no need for php
var url='https://www.googleapis.com/books/v1/volumes?q='+isbn;
$.getJSON(url,function(data){
$('.result').empty();
$.each(data.items, function(entryIndex, entry){
var html = '<div class="results well">';
html += '<h3>' + entry.volumeInfo.title + '</h3>';
html += '<h5>' + entry.volumeInfo.subtitle + '</h5>';
html += '<p>' + entry.volumeInfo.authors + '</p>';
html += '<p>' + entry.volumeInfo.description + '</p>';
$('.result').append(html);
});
});
});
});
AJAX
$.ajax({
type: 'POST',
url: 'addIsbnScript.php',
data: {
'isbn' : isbn,
'title' : entry.volumeInfo.title,
'subtitle' : entry.volumeInfo.subtitle,
'authors' : JSON.stringify(entry.volumeInfo.authors),
'description' : entry.volumeInfo.description
},
success: function () {
$("#add").prop('disabled', true);
}
});
PHP
$isbn = $_POST['isbn'];
$title = $_POST['title'];
$subtitle = $_POST['subtitle'];
$authors = $_POST['authors'];
$decoded_authors = json_decode($authors);
print_r($decoded_authors);
$description = $_POST['description'];
$query = $conn->prepare("INSERT INTO `isbn` (isbn_num,title,subtitle,authors,description) VALUES (?,?,?,?,?)");
$query->bind_param('issss',
$isbn,
$title,
$subtitle,
$decoded_authors,
$description
);
JSON
"volumeInfo":{
"title":string,
"subtitle":string,
"authors":[
string
],
"publisher":string,
"publishedDate":string,
"description":string,
"industryIdentifiers":[
{
"type":string,
"identifier":string
}
],
"pageCount":integer,
"dimensions":{
"height":string,
"width":string,
"thickness":string
},
"printType":string,
"mainCategory":string,
"categories":[
string
],
"averageRating":double,
"ratingsCount":integer,
"contentVersion":string,
"imageLinks":{
"smallThumbnail":string,
"thumbnail":string,
"small":string,
"medium":string,
"large":string,
"extraLarge":string
},
"language":string,
"previewLink":string,
"infoLink":string,
"canonicalVolumeLink":string
},
如果代码很业余,请原谅我是 JS 新手,这只是为了个人发展。
【问题讨论】:
-
'authors' : JSON.stringify(entry.volumeInfo.authors),怎么样?然后在服务器端解析它并继续? -
感谢@Rory,它现在以以下格式发送值 ["Chris Cleave","Philippa Gregory","Sarah Pekkanen - 所以我将看看解析 JSON 服务器端。我很快就会更新。
-
你可以在服务器端使用php.net/manual/en/function.json-decode.php来解码。
标签: javascript php jquery ajax json