[英]javascript jquery and using eval
我目前正在使用jquery插件讀取數據文件(data.html)
data.html具有以下格式
[10,20,30,40,50]
我的jQuery數據請求和返回值的JavaScript如下
function test(){
var result=$.ajax({
url:'data.html',
type:'get',
dataType:'text',
async:false,
cache:false
}).responseText
return result;};
var my=test();
alert(my[0])
我想以數組格式獲取這些值,即我希望my [0]的值為10,但我卻得到“ [”。 如果我使用評估功能
my=eval(test());
我可以得到10,但是還有其他更好的方法將返回的ajax調用存儲到數組而不是字符串中嗎?
謝謝
我嘗試了以下答案,但我有點困惑,以下代碼導致myArray為null(在螢火蟲中),但是我將async:false設置為有效。 為什么我需要async:false將值存儲到數組中? (http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req)
jQuery.extend({getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;}
});
return result;}});
myArray=$.getValues("data.html");
alert(myArray[1]);
您不需要eval
。 只需指出正確的dataType: 'json'
:
function test() {
return $.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
async: false,
cache: false
}).responseText;
}
var my = test();
alert(my[0]);
甚至更好地異步執行:
function test() {
$.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
}
});
}
test();
我認為jquery $ .getScript('data.html',function(){alert(“ success” + $(this).text())}可能更簡單。我沒有時間嘗試,所以如果在正確的軌道上,改善這個答案,如果不是,我現在很高興學習...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.