douzhang7603 2017-03-07 19:43
浏览 120
已采纳

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

I would like to place the data from the $data variable (ajax.php) into my this.products[ ] (store.js) array in the javascript file. How would i do this? Bearing in mind they are in to seperate files, can i link the two?

The ajax.php file returns the database data in webpage as follows:

[{"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 - originally this.product[ ] contained LocalStorage values, but i would like then to contain the values from the JSON file in order from the database table.

//----------------------------------------------------------------
// 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条回答 默认 最新

  • doucitao2944 2017-03-07 20:01
    关注

    You need to use AJAX. Here are two options (you would use this in your store.js file)

    Using 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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 需要帮我远程操控一下,运行一下我的那个代码,我觉得我无能为力了
  • ¥20 有偿:在ubuntu上安装arduino以及其常用库文件。
  • ¥15 请问用arcgis处理一些数据和图形,通常里面有一个根据点划泰森多边形的命令,直接划的弊端是只能执行一个完整的边界,但是我们有时候会用到需要在有很多边界内利用点来执行划泰森多边形的命令
  • ¥30 在wave2foam中执行setWaveField时遇到了如下的浮点异常问题,请问该如何解决呢?
  • ¥750 关于一道数论方面的问题,求解答!(关键词-数学方法)
  • ¥200 csgo2的viewmatrix值是否还有别的获取方式
  • ¥15 Stable Diffusion,用Ebsynth utility在视频选帧图重绘,第一步报错,蒙版和帧图没法生成,怎么处理啊
  • ¥15 请把下列每一行代码完整地读懂并注释出来
  • ¥15 寻找公式识别开发,自动识别整页文档、图像公式的软件
  • ¥15 为什么eclipse不能再下载了?