简体   繁体   English

使用Javascript从PHP解析JSON并将值动态推送到数组中

[英]Parse JSON from PHP by Javascript and Push the values into array dynamically

i got an array : 我有一个数组:

var sampleitems =[];

i get json data from url which returns values 我从返回值的网址中获取json数据

 WinJS.xhr({
        type: "GET",
        url: "http://some_webpage.php", 

    }).then(function (success) { 
// DYNAMICALLY PUSH CONTENTS TO ARRAY 'sampleitems'
    }, 
  function (error) {
      document.getElementById("check").innerText = "vada pochu";
  }

i need the array to look like: 我需要数组看起来像:

var sampleitems = [
{ key: "group1", title: "Group Title: 1", subtitle: "Group Subtitle: 1", backgroundImage: darkGray, description: groupDescription } ];

How can i add values to the sample items dynamically and how my PHP page should return JSON in which format ? 如何动态地将值添加到示例项,我的PHP页面应如何以哪种格式返回JSON?

You should look at PHP's JSON_ENCODE() function. 您应该查看PHP的JSON_ENCODE()函数。 The code below should output the JSON that you need (I haven't checked that it works). 下面的代码应该输出您需要的JSON(我没有检查它是否有效)。

$sampleitems=array(
 array(
  'key'=>'group1',
  'title'=>'Group Title: 1',
  ...
 )
);

echo json_encode($sampleitems);

sampleitems.push({键:“ group1”,标题:“ Group标题:1”,字幕:“ Group字幕:1”,backgroundImage:darkGray,描述:groupDescription});

make an array an perform json_encode like: 使数组执行json_encode,例如:

$sampleitems = array(
        'key' => 'group1',
        'title' => 'Group Title: 1',
        'subtitle' => 'Group Subtitle: 1',
        'backgroundImage' => 'darkGray',
        'description' => 'groupDescription'
    );
    echo '['.json_encode($sampleitems).']';

result: 结果:

[{"key":"group1","title":"Group Title: 1","subtitle":"Group Subtitle: 1","backgroundImage":"darkGray","description":"groupDescription"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM