Setting ajax url for jQuery in JS file using ASP.NET MVC

前端 未结 5 1519
星月不相逢
星月不相逢 2020-12-12 16:43

When doing a Ajax call to an MVC action currently I have my javascript inside the View, not inside its own JS file.

It is then very easy to do this:

         


        
5条回答
  •  醉酒成梦
    2020-12-12 17:11

    Use the module pattern.

    
    // separate js file
    var PAGE_MODULE = (function () {
      var url = {},
          init = function(url) { ... },
          load = function() {
          $.ajax({
               url: url,
               ...
               });
          }
    
          return { init: init };
    })();
    
    
    
    // calling init goes on the page itself
    PAGE_MODULE.init(" %: Url.Action(...) %>");
    
    

    In general the inline onclick handler is not good javascript as you are using a global function.

    
    onclick='doAjax( 
    

    I recommend reading http://jqfundamentals.com/book/index.html#N20D82 to get a better handle on the module pattern.

提交回复
热议问题