$.getJSON("/data/data/com.android.tcptest/files/BPL.json", function(data) {
var i = 0, dataSize = data.length, tmpArray = [];
for(i; i < dataSize; i++){
tmpArray.push ([data[i].Time.substring(0, data[i].Time.length -2).replace(/:/g, ""),data[i].Bid ]);
}
return tmpArray;
});
$.plot($("#chart"), [ tmpArray ]);
How can I use tmpArray
outside get开发者_开发问答JSON()
function. My programme doesn't work.
Thanks!
Initialize tmpArray outside of the getJSON
block.
Edit: Quentin is right, the array would be empty. You'll also need to make the request synchronous. I wrote the following example, hope it helps: http://jsfiddle.net/mXHfC/
Asynchronous JavaScript and XML is asynchronous.
You can't return from it, any more then you could return from:
$('button').click(function () {
return tmpArray;
});
$.plot($("#chart"), [ tmpArray ]); /* Does this method really expect an array consisting of a single value that is another array? */
The code in the callback won't execute until after the HTTP response has arrived (or the button has been clicked).
Do the work inside the callback.
$.getJSON("/data/data/com.android.tcptest/files/BPL.json", function(data) {
var i = 0, dataSize = data.length, tmpArray = [];
for(i; i < dataSize; i++){
tmpArray.push ([data[i].Time.substring(0, data[i].Time.length -2).replace(/:/g, ""),data[i].Bid ]);
}
$.plot($("#chart"), [ tmpArray ]);
});
getJSON is asynchronous, you can not use the array before the function is returned!
$.getJSON("/data/data/com.android.tcptest/files/BPL.json", function(data) {
var i = 0, dataSize = data.length, tmpArray = [];
for(i; i < dataSize; i++){
tmpArray.push ([data[i].Time.substring(0, data[i].Time.length -2).replace(/:/g, ""),data[i].Bid ]);
}
$.plot($("#chart"), [ tmpArray ]);
//return tmpArray;
});
精彩评论