开发者

Parse JSON ajax var

I like translate my json-Data to an JS object or assign it to a variable..

开发者_运维百科
$.ajaxSetup({
type: "POST",
url: "_class/queries.php",
dataType:"json"
});

var obj;    

$.ajax({
   data: querystring,
   success: function(data){

     console.log(data);

     alert(data[0].vname);

     //obj = JSON.parse(JSON.stringify(data));

     obj = data;

     console.log(obj[0].vname);//<-- prints the expected property 
   }

 });

console.log("return "+obj);//<-- undefined?
return obj;

}

the alert print out the right property-value but somehow the eval-function produces an pars error? I've tryed jQuery.parseJSON but wont work either?


The json variable contains already parsed value - the data returned by the server. Why do you you need to eval it?

obj = data;

is enough.


Set the type property of $.ajax() to json:

$.ajax({
    data: querystring,
    dataType: "jsonp",
    success: function(json) {
        console.log(json);
        alert(json[0].vname);
        obj = eval("(" + json + ")");
    }
});

From the manual:

"json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)

eval() shouldn't be used if possible - in your case, unless your JSON data contains actual Javascript code to execute you don't need to eval() it.

Also, the AJAX call is asynchronous - this means that the AJAX request is made out-of-order of usual program execution. In your code that means at return obj; the obj variable doesn't have the same value as it will after the AJAX call has returned with data from the server and assigned the return of the eval() call to obj. The solution to this is event-driven programming - in your case, have the success function call the next "event" that you'd like to occur, or use the AJAX function to populate a variable (in the global scope, preferably namespaced) that another event polls for (using a timing event such as setInterval()).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜