简体   繁体   English

json到javascript数组并存储以供外部ajax调用使用

[英]json to javascript array and storing for outside ajax call use

Hey was hoping for some quick help, 嘿,希望能有一些快速的帮助,

My overall goal is to retrieve a php array and store it into a javascript array using an ajax call. 我的总体目标是检索一个php数组,并使用ajax调用将其存储到javascript数组中。 I am new to all of this, so please bear with me. 我是这一切的新手,所以请多多包涵。

My ajax call is successful such that it returns the echo json_encode(array); 我的ajax调用成功,因此它返回echo json_encode(array); and goes to the success function. 并转到成功功能。

I am confused on how to take json encoded data and store it into a javascript array that I am able to use outside the ajax call. 我对如何获取json编码的数据并将其存储到我可以在ajax调用之外使用的javascript数组中感到困惑。

$.ajax({
        type: "POST",
        url: myurl.php
        data: {var1: var1, var2:var2},
        dataType: "json",
        success: function(data)
        {
          console.log(data);
          var simplified = JSON.stringify(data);
          console.log(simplified);
          var jsonObj = $.parseJSON('[' + simplified + ']');
        },
    });

The console logs gives me; 控制台日志给了我;

Object {63: Object, 64: Object, 65: Object}

and

{"63":{"Comment":"tc 1"},"64":{"Comment":"tc 2"},"65":{"Comment":"tc 3"}}

respectively. 分别。

I would like an array in this form; 我想要这种形式的数组;

63
  Comment=>"tc 1"
64
  Comment=>"tc 2"
65 
  Comment=>"tc 3"

Thanks for any sort of help! 感谢您的任何帮助!

UPADTE: Any suggestions on how I would access the created array outside of the ajax call? UPADTE:关于如何在ajax调用之外访问创建的数组的任何建议? Everytime I try to, it says it is undefined. 每次尝试时,它都未定义。

You have to iterate through the object's property and create an array: 您必须遍历对象的属性并创建一个数组:

var myObj = {
    1: [1, 2, 3],
    2: [4, 5, 6]
};

var array = $.map(myObj, function(value, index) {
    return [value];
});


console.log(array);

Here you are: 这个给你:

var data = JSON.parse('{"63":{"Comment":"tc 1"},"64":{"Comment":"tc 2"},"65":{"Comment":"tc 3"}}');
alert(data[63].Comment); // to access

Hope this help. 希望能有所帮助。

Your data variable is already an object. 您的data变量已经是一个对象。 jQuery internally parsed the JSON into an object. jQuery内部将JSON解析为一个对象。 If you want to make it an array, here you go: 如果要使其成为数组,请执行以下操作:

$.ajax({
  type: "POST",
  url: myurl.php
  data: {var1: var1, var2:var2},
  dataType: "json",
  success: function(data)
  {
    var arr = [];

    $.map(data, function(value) {
      arr.push(value);
    });
  }
});

But if you still need the key (you had on server-side) just keep it like that and access it like data[63] . 但是,如果您仍然需要密钥(您在服务器端拥有),只需保持该密钥不变,然后像data[63]一样访问它data[63] Javascript doesn't have associative arrays, here they are objects, semanticaly called array-like objects. Javascript没有关联数组,在这里它们是对象,在语义上称为类数组对象。

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

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