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

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测