开发者

Json path triggers local, but not when published. Why?

开发者 https://www.devze.com 2023-02-12 22:00 出处:网络
I have a .js file that works fine locally, but I am somehow having path problems when I commit and add to my server. I have \"Home\" for the controller name, and \"LoadTable\" for the JsonResult funct

I have a .js file that works fine locally, but I am somehow having path problems when I commit and add to my server. I have "Home" for the controller name, and "LoadTable" for the JsonResult function.

$(document).ready(function () {
$('#tableClick').click(function () {
    $.post("Home/LoadTable", $('#FormTable').serialize(), funct开发者_StackOverflow中文版ion (data) {
        alert("test");
    }, 'json');
});
});

Should I have the path name be something else when published? If so how do I toggle from local to server version in my webconfig, if possible?

Is there another option?


  1. /Home/LoadTable = absolute = example.com/Home/LoadTable
  2. Home/LoadTable = relative = {current_url}/HomeLoadTable


With Val's help, I was able to come up with the following.

var pathName = window.location.pathname;
if (pathName == "/") { pathName = ""; }
$.post(pathName + "Home/LoadTable", $('#FormTable').serialize(), function (data) { 
    alert("test");
}, 'json');    


Never hardcode urls. Always use Url helpers when dealing with urls:

$.post(
    '<%= Url.Action("LoadTable", "Home") %>', 
    $('#FormTable').serialize(), 
    function (data) {
        alert('test');
    }, 
    'json'
);

Another possibility is to have a link somewhere on your page:

<%= Html.ActionLink("Load table", "LoadTable", "Home", null, new { @class = "loadTable" }) %>

which you would AJAXify:

$(function() {
    $('.loadTable').click(function() {
        $.post(this.href, $('#FormTable').serialize(), function (data) {
            alert('test');
        }, 'json');
        return false;
    });
});
0

精彩评论

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