AJAX调用返回' undefined'

时间:2015-04-28 11:24:49

标签: jquery ajax json undefined

AJAX调用如下:

$.get('file.php')
.done(function(data) {
    console.log(data);
});

控制台返回:

[{"0":"PS001","code":"PS001"}]

但是,如果将日志修改为console.log(data.code),则会返回undefined。另外,使用each遍历JSON:

.done(function, data) {
    $.each(data, function(key, value) {
        console.log(value.code);
    });
)};

导致以下错误:

[Error] TypeError: [{"0":"PS001","code":"PS001"}] is not a valid argument for
'in' (evaluating 'b-1 in a')

JSON看起来很好,所以不确定问题是什么?

4 个答案:

答案 0 :(得分:2)

public class MainActivity extends Activity { int [] AccVal = new int[3]; TextView acceleration; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // this one will call constructor of AccelerometerClass and initialise sensors AccelerometerClass acc = new AccelerometerClass(getApplicationContext()); acceleration = (TextView)findViewById(R.id.acceleration); // access like this here acceleration.setText("X: "+acc.getValue(0)+ "\nY: "+acc.getValue(1)+ "\nZ: "+acc.getValue(2)); } } 返回字符串。

详细了解JSON_ENCODE

您应该将 JsonArrayString 转换为 JsonArray

JSON_ENCODE

答案 1 :(得分:1)

试试这个,因为你的代码返回了json数组。

console.log(data[0].code);  //If you getting JSON format

OR

console.log(JSON.parse(data)[0].code);  //If you getting JSON as String

<强> Demo

答案 2 :(得分:1)

试试这个:

$.get('file.php')
.done(function(data) {
    var json = JSON.parse(data)[0];
    console.log(json .code);
});

答案 3 :(得分:1)

这是一个json字符串。你需要先解析它。试试 -

data = $.parseJSON(data);
$.each(data, function(key, value) {
    console.log(value.code);
});