我发现了很多关于这个主题的问题而且投票很少,但到目前为止我似乎无法得到任何有效的答案。我已经在Web服务器上创建了一个PHP页面到一个application / json中,它将mysqli查询转换为数组,并使用json_encode对其进行编码,以便它现在是一个JSON对象。我现在正在尝试使用javascript解码JSON对象,但我能找到的唯一解决方案是处理数组而不是对象。最后,我想解码JSON并迭代它,以便我可以将数据插入到客户端上的Sqlite数据库中。我很难在客户端上获得任何结果,除非能够对JSon进行字符串化,以便我可以看到它已被检索。我的代码如下:
Web服务器retrieveJSON.php页面
<?php header('Content-Type: application/json');
$mysqli= new mysqli("host","user","password","database");
mysqli_select_db($mysqli,"database");
$query = "SELECT * FROM AppCustomers";
$result = mysqli_query($mysqli,$query) or die('Errant query: '.$query);
$customers = array();
if(mysqli_num_rows($result)) {
while($customer = mysqli_fetch_assoc($result)) {
$customers[] = array('customer'=>$customer);
}
}
$json_array = array('customers'=>$customers,);
echo json_encode($json_array);
mysqli_close($mysqli);
?>
客户端Javascript
<script>
$.ajax({
url : 'http://webserver/retrieveJSON.php',
dataType : 'json',
type : 'get',
success : function(Result){
//ResultAlert = JSON.stringify(Result);
//alert(ResultAlert);
}
});
</script>
当我对结果进行字符串化时,我得到了以下JSON对象的长版本:
{"customers":[{"customer":{"id":"1","customerName":"Customer Alpha","customerID":" custA","customerAddress":" Alpha Way","customerCity":" Alpha","customerState":" AL","customerZip":"91605"}},{"customer":{"id":"2","customerName":"Customer Beta","customerID":" CustB","customerAddress":" Beta Street","customerCity":" Beta","customerState":" BE","customerZip":"91605"}}]}
我有一个数据库,并且已经设置了以下插入功能。
function insertCustomer(customerName, customerID, customerAddress, customerCity, customerState, customerZip) {
db.transaction(function (tx) {
tx.executeSql('INSERT INTO Customers (customerName, customerID, customerAddress, customerCity, customerState, customerZip) VALUES (?, ?, ?, ?, ?, ?)', [customerName, customerID, customerAddress, customerCity, customerState, customerZip],CountReturns);
});
};
如何将对象重新转换为数组,以便我可以遍历它并将每个字段插入到我的Sqlite数据库中?换句话说,我用//替换// stringify部分?我希望这个问题不是太局部化,但我试图将整个过程布局,以防其他人试图做同样的事情。此过程中的任何其他提示或建议也受到欢迎。感谢。
感谢Quentin我能够使用以下代码代替stringify访问数组并将字段输入数据库;但是,由于某种原因,所有输入都是未定义的。
for (var i = 0, len = Result.customers.length; i < len; ++i) {
var customer = Result.customers[i];
insertCustomer(customer.customerName, customer.customerID, customer.customerAddress, customer.customerCity, customer.customerState, customer.customerZip);
}
答案 0 :(得分:2)
customers
。您可以使用Result.customers
。