我发现很多关于这个主题的问题只有很少的投票,但我似乎无法得到任何迄今为止的工作答案。我在Web服务器上创建了一个PHP页面,将其转换为application/json,将mysqli查询转换为数组,并使用json_encode对其进行编码,使其成为JSON对象。我现在正在尝试使用javascript解码JSON对象,但唯一能找到的解决方案是处理数组而不是对象。最终,我想解码JSON并遍历它,以便我可以将数据插入到客户端上的Sqlite数据库中。我很难在客户端上得到任何结果,除非能够对JSon进行字符串化,以便我能够看到它已被检索。我的代码如下:使用Javascript解码PHP编码的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);
}
您正在寻找['JSON.parse'](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse)。 – 2013-05-03 16:32:13