javascript jquery and using eval

ぃ、小莉子 提交于 2019-12-24 23:42:46

问题


i am currenty using jquery plugin to read a data file (data.html)

data.html has below format

[10,20,30,40,50]

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])

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());

i can get 10, but is there any other better way to store the returned ajax calls into an array instead of string?

Thanks

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]);

回答1:


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();



回答2:


I think jquery $.getScript('data.html',function(){alert("success"+$(this).text())} might be simpler. I have not had time to try it so if I'm on right track, improve this answer, if not I'm happy to learn now...



来源:https://stackoverflow.com/questions/5484193/javascript-jquery-and-using-eval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!