0

Is there a way to call a JavaScript file in an Ajax call and use logic in that file?

For instance, I am currently calling a JSON file using Sencha Touch like this:

Ext.Ajax.request({
    url : 'resources/data/userdata.json',
        headers : {
            "Content-Type" : "application/json"
        },
        callback : function (options, success, response) {
            obj = JSON.parse(response.responseText);
            for (var i = 0; i < obj.length; i++) {
                console.log(obj[i].name);
            }
        }
    });

But is it possible to call a JavaScript file and do some logic in that file maybe based on the parameters sent in?

I know I can do this with server files (ASP.NET, PHP, etc.)... I was just wondering if this is possible using a JavaScript file.

I tried calling a window.onload function or using an immediate function, but I still get ALL the text back in the file instead of just the JSON that I am trying to return...:

(function(){
    return '[{ "name": "todd", "lastname":"vance"}, { "name": "joe", "lastname":"schmoe"}] ';
})();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Todd Vance
  • 4,627
  • 7
  • 46
  • 66

2 Answers2

1

You need to eval the result you get from the Ajax, eval(myajaxresponse);. This could call the JavaScript code in it, or it could register the functions so you can use them later. You can get more information in Stack Overflow question Calling a JavaScript function returned from an Ajax response.

Community
  • 1
  • 1
Luis Tellez
  • 2,785
  • 1
  • 20
  • 28
1

You could always assign a string representation of the function to a key in the JSON:

methods.json usage (based on your code):

return '{method: ["(function(arg1, arg2){// do stuff})", "(function(arg1){// do other stuff})"]}';

...

var args = [arg1, arg2, argsetc];
Ext.Ajax.request({
    url: 'resources/data/userdata.json',
    headers: {
            "Content-Type": "application/json"
    },
    callback: function (options, success, response) {
        obj = JSON.parse(response.responseText);
        for (var i = 0; i < obj.method.length; i++) {
            var method = eval(obj.method[i]);
            method.apply(method, args); // Executes the method with arguments
        }
    }
});

Also make sure to include the preceding and following {} to the JSON so it will be parsed and work as expected. ;)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Nolo
  • 846
  • 9
  • 19