javascript jQuery和使用eval [英] javascript jquery and using eval
问题描述
我目前正在使用jquery插件读取数据文件(data.html)
i am currenty using jquery plugin to read a data file (data.html)
data.html具有以下格式
data.html has below format
[10,20,30,40,50]
我的jquery数据请求和返回值的javascript如下
my jquery data request and the javascript to return values is below
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,但我却得到"[". 如果我使用评估功能
i want to get these values in the array format i.e i want my[0] to be value 10, but instead i get "[". If i use eval function
my=eval(test());
我可以得到10,但是还有其他更好的方法将返回的ajax调用存储到数组而不是字符串中吗?
i can get 10, but is there any other better way to store the returned ajax calls into an array instead of string?
谢谢
我尝试了以下答案,但我有些困惑,以下代码导致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)
i tried the below answer and i am bit puzzled, the follow code results in myArray is null (in firebug), but i put async:false then it works. why do i need async:false to store the values into array ? (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'
:
You don't need eval
. Just indicate the proper dataType: 'json'
:
function test() {
return $.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
async: false,
cache: false
}).responseText;
}
var my = test();
alert(my[0]);
或者甚至更好地异步执行:
or even better do it asynchronously:
function test() {
$.ajax({
url: 'data.html',
type: 'get',
dataType: 'json',
cache: false,
success: function(result) {
alert(result[0]);
}
});
}
test();
这篇关于javascript jQuery和使用eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!