Javascript ajax回调后,变量中的json变为[object]

Javascript ajax回调后,变量中的json变为[object],javascript,Javascript,在js中,我会: google.maps.event.addListener(circle, 'click', function(event) { var saveData = dataSet[a]; console.log(saveData); 这给了我控制台中的各种json对象,比如 {data: Array(48), Province/State: "Suffolk County, NY", Country/Region: "US", Lat: 40.9849, Long:

在js中,我会:

 google.maps.event.addListener(circle, 'click', function(event) {
   var saveData = dataSet[a];
   console.log(saveData);
这给了我控制台中的各种json对象,比如

{data: Array(48), Province/State: "Suffolk County, NY", Country/Region: "US", Lat: 40.9849, Long: -72.6151}
{data: Array(48), Province/State: "Ulster County, NY", Country/Region: "US", Lat: 41.8586, Long: -74.3118}
然后,我在ajax中检查其他内容,如果成功,我将saveData作为按钮的数据属性,但它会给出[object]

如果我在ajax之后,在告诉按钮获取该变量作为数据属性之前,在控制台中执行检入操作,那么

$.ajax({
 url: ajax_url,
 type: 'post',
 data: { action: 'data_savedInternal', id: saveThis },
 success: function(data) {
  console.log(saveThis);
我得到了正确的json

{data: Array(48), Province/State: "Suffolk County, NY", Country/Region: "US", Lat: 40.9849, Long: -72.6151}
{data: Array(48), Province/State: "Ulster County, NY", Country/Region: "US", Lat: 41.8586, Long: -74.3118}

请通过json.stringify将json转换为字符串

不能将对象作为数据属性存储在dom中。但是,您可以将数据保存到数据对象的索引数组中,然后将索引存储在数据id上,然后使用该索引稍后访问数据

例如:

var globalDataStore = [];

google.maps.event.addListener(circle, 'click', function(event) {
   var saveData = dataSet[a];
   console.log(saveData);

   var index = globalDataStore.length;// the length of the array prior to push is equal to the index of your new data object after push occurs.
   globalDataStore.push(saveData);// push the data into the array

   $.ajax({
        url: ajax_url,
        type: 'post',
        data: { action: 'data_savedInternal', id: saveThis },
        success: function(data) {
            console.log(saveThis);
            // now update your button with the index
            // you are not showing how you do that, so below is just pseudo code
            // pseudocode: <button data-id="'+index+'">
        }
    });

});

@r3wt我尝试将其设置为一个类似savData=saveData.toString的字符串,但是,什么也没有,我尝试使用JSON.parsesaveData,但是什么也没有。所以我在这里问。你能尝试使用Json.StrignifySaveDataCast吗?当你将一个对象转换成字符串时,你会得到“[object object]”。这也是Object.prototype上toString方法的结果。如果希望将其序列化为JSON,请使用JSON.stringify。这些都是非常基本的东西。@JaredSmith谢谢,真的认为使用saveData.toString会有效吗?真的认为使用saveData.toString会有效吗。谢谢你this@rob.m您可以像前面提到的其他海报一样,将其保存到dom中作为json,但如果json包含html,则可能会破坏您的ui。您可以使用JSON.stringifysaveData执行此操作;但我强烈建议不要这样做。我以前做过这样的事,不过现在我宁愿把它留在记忆中,以便妥善保管。如果我需要它持续存在,有本地存储、cookies等。我确实认为使用saveData.toString会有效。谢谢你,是的,你用ToString就快到了。
//assume this is one of your buttons
button.onClick(e=>{
    var index = e.target.getAttribute('data-id');
    index = parseInt(index,10);//convert to int, because its a string from being in dom.
    var saveData = globalDataStore[index];
    console.log(saveData);
    //now do something with your data
});