0

I have a web application that uses VB.NET MVC for the server side code. I set up the client side JavaScript to easily send and receive data to the server Controller functions. Basically what I did was create a JavaScript "request" object that uses Ajax to call a controller function and pass in parameters. I let MVC do all of the serialization for me. Then the controller function returns a JSON, usually with a block of HTML as a string. Since I am handling all of the ajax calls in one place, I can't figure out a good way to handle the responses. When the ajax response comes back, I have no way of knowing which request it came from. The website has a lot going on so the responses all need to be handled differently and all return different data.

Right now what I do is in the controller function I send back some key along with the block of HTML, then in the ajax complete function I check for all of these specific keys. Doing it this way makes the javascript code difficult to manage.

var postData =  { id=0 };
 $.ajax({
   type: "POST",
   url: "/Controller/Action/"
   data: postData
}).done(function (data) {
   if (data.Foo) {
    Foo(data);
   } else if(data.Bar) }
    Bar(data);
   }
});

I am having trouble researching this because I don't know which keywords to look up. I think I'm going to try and do something where I call the function names dynamically in the ajax done function, but I was wondering if there are any existing libraries or code examples that do larger scale ajax request functions like this.

user1333935
  • 61
  • 1
  • 6

1 Answers1

0

Maybe the problem comes from the idea of "doing all the stuff in one place". I can imagine that it will be very difficult to maintain your code once you have 40 chained if...else if... in one method. Maybe splitting things up a bit wont hurt after all.

Anyway, one way of doing it the way you want it would be instead of passing a key, passing the name of the javascript function as a delegate. Then call window[data.funcName](data); in done().

Say your json is

{
    foo: "bar",
    funcName: "DoMyFoo"
}

This is how your call would look like :

var postData =  { id=0 };
 $.ajax({
   type: "POST",
   url: "/Controller/Action/"
   data: postData
}).done(function (data) {
   window[data.funcName](data);
});

function DoMyFoo(d){
    //Do your specific stuff here
    alert(d.foo);
}

See this question How to execute a JavaScript function when I have its name as a string for info and examples.

Edit: If your functions lies within an object instance instead of the global namespace, say obj, you can call it the same way with obj['myFunction'](args)

Community
  • 1
  • 1
Drewman
  • 947
  • 11
  • 23