tags:

views:

287

answers:

1

I'm using JSONP to get data from a server.

The more typical method of dealing with this is to get the data and then have the javascript determine what to do with the data (updating a div, etc)

However, instead of responding with simple data, the server is responding with the actual jQuery code that needs to be executed. How can I make my javascript accept that response and then actually execute it? I've done this very successfully with Mootools (using evalScripts), but I can't figure it out in jQuery.

The benefits of this is that the client side code is much smaller and less work has to be done in the browser.

Example:

    $.getJSON("http://appbeacon.com/index.php?model=blah_blah_blah", function(data){
 $.each(data, function(i,item){
  console.log(item);
  // Need to execute "item" ??????
 });
});

Example Response (No Longer JSON Encoded):

$("#1_cmd_group").remove();
$("#2_cmd_group").remove();
$("#3_contents").html("<li>blah blah blah");
+2  A: 
eval(item);

give that a go

Darko Z
JSON is not meant to be code. You should view it interchangeably with XML.
Dr. Zim
Thank you. That was a lot easier than I expected. I edited my original post with the Mootools method of doing this, then it dawned on me to search google for "jquery evalScripts". I came up with several convoluted solutions. Your answer was right on.Thanks,Justin
Justin
Glad I could help. Just one note however. eval() is relatively slow compared to executing normal code so just be cautious when using it.
Darko Z