将数据从JSON数组放入Javascript数组

时间:2017-03-07 19:43:24

标签: javascript php json ajax

我想将来自$ data变量(ajax.php)的数据放入javascript文件中的this.products [](store.js)数组中。我该怎么办?请记住,他们是分开的文件,我可以链接这两个?

ajax.php文件在网页中返回数据库数据,如下所示:

[{"0":"100001","SKU":"100001","1":"Key Ring","Name":"Key Ring","2":"Personalised Key Ring","Description":"Personalised Key Ring","3":"5","Price":"5"}

ajax.php

<?php
//database settings
$connect = mysqli_connect("localhost", "root", "", "wrightr");

$result = mysqli_query($connect, "select * from storeitems");

$data = array();

while ($row = mysqli_fetch_array($result)) {
  $data[] = $row;
}
    echo json_encode($data);
?>

store.js - 最初this.product []包含LocalStorage值,但我希望从数据库表中按顺序包含JSON文件中的值。

//----------------------------------------------------------------
// store (contains the products)
//
function store() {
    this.products = [
 //example   new product (**field1**, **field2**, **field3**, etc...),
 //example   new product (**field1**, **field2**, **field3**, etc...),        
}
store.prototype.getProduct = function (sku) {
    for (var i = 0; i < this.products.length; i++) {
        if (this.products[i].sku == sku)
            return this.products[i];
    }
    return null;
}

1 个答案:

答案 0 :(得分:1)

您需要使用AJAX。以下是两个选项(您可以在store.js文件中使用此选项)

使用jQuery [docs]

$.get('ajax.php', function(resp){
   // do something with resp
   console.log(resp) // [{"0":"100001"...
})

Vanilla JavaScript [docs]

var req = new XMLHttpRequest();
req.addEventListener("load", function(){
    if(req.status === 200) { 
        var resp = JSON.parse(req.response)
    }
});
req.open("GET", "ajax.php");
req.send();