使用JSON从Ajax调用获取未定义数组类型

时间:2022-10-18 07:41:29

So I'm making a webapplication where you can play sudoku but the back-end is in Java. I made a servlet to communicate with my Jquery trough ajax.

我在做一个webapplication你可以玩数独但是后端是Java的。我制作了一个servlet来与Jquery通过ajax进行通信。

I'm sending my generated array (the sudoku) to my webapp with this servlet trough Ajax. But when I do a typeof it seems to be undefined. Which means I cannot do any operations with the array

我用Ajax这个servlet把生成的数组(sudoku)发送到我的webapp。但是当我做一个类型时,它似乎是没有定义的。也就是说我不能对数组做任何操作

This is my Ajax call:

这是我的Ajax调用:

    $.ajax({
    url:"/2017_S2_Group_18/API/*",
    dataType:"json",
    success: function(data) {
        for(var i = 0; i<81;i++){
            originalSudoku[i] = $(data).attr("sudokuArray")[i];
            changedSudoku[i] = $(data).attr("sudokuArray")[i];
        }           
    }
});

orginalSudoku is the array that cannot be modified and changedSudoku is the array that is going to be modified.

orginalSudoku是不能修改的数组,而changedSudoku是将要修改的数组。

This is the output I get by browsing to the URL from my Ajax call.

这是通过浏览Ajax调用的URL获得的输出。

{"sudokuArray":[7,6,8,1,9,2,3,4,5,1,9,2,4,3,5,6,7,8,4,3,5,7,6,8,9,1,2,8,7,9,2,1,3,4,5,6,2,1,3,5,4,6,7,8,9,5,4,6,8,7,9,1,2,3,9,8,1,3,2,4,5,6,7,3,2,4,6,5,7,8,9,1,6,5,7,9,8,1,2,3,4]}

{“sudokuArray”:[7 6 8,9,2,3,4,5,1,2,4,3,5,6,7,8,4,3,5,7,6,8,9,1、2、8、7、9,2,1,3,4,5,6,2,1,3,5,6,7,8,9,5、4、6、8、7、9,1、2、3、9、8、1,3,4,5,6,7,3、2、4、6、5、7,8,9,1、6、5、7、9、8、1,2,3,4]}

How can I parse/change my type to either string or char or integer?

如何将类型解析/更改为字符串或char或integer?

1 个解决方案

#1


2  

The issue is because data is an object, and you're trying to use jQuery's attr() method, intended for DOM elements, to access a property of it. That's not going to work.

问题在于,数据是一个对象,您正在尝试使用jQuery的attr()方法(用于DOM元素)来访问它的属性。这行不通。

Instead, you can access the properties of data as you would any normal object in Javascript. Try this:

相反,您可以像访问Javascript中的任何普通对象一样访问数据的属性。试试这个:

success: function(data) {
  for (var i = 0; i < data.sudokuArray.length; i++) {
    originalSudoku[i] = data.sudokuArray[i];
    changedSudoku[i] = data.sudokuArray[i];
  }           
}

#1


2  

The issue is because data is an object, and you're trying to use jQuery's attr() method, intended for DOM elements, to access a property of it. That's not going to work.

问题在于,数据是一个对象,您正在尝试使用jQuery的attr()方法(用于DOM元素)来访问它的属性。这行不通。

Instead, you can access the properties of data as you would any normal object in Javascript. Try this:

相反,您可以像访问Javascript中的任何普通对象一样访问数据的属性。试试这个:

success: function(data) {
  for (var i = 0; i < data.sudokuArray.length; i++) {
    originalSudoku[i] = data.sudokuArray[i];
    changedSudoku[i] = data.sudokuArray[i];
  }           
}