服务器上的AJAX成功函数

And*_*ich 6 javascript c# asp.net-mvc jquery razor

这适用于我的开发机器,但不适用于生产服务器.我试图用ajax更新一些div,但它们没有更新,虽然其他部分工作正常.我在服务器上使用IIS 6.当我使用firebug在服务器端调试此代码时,它不会触及我添加到success函数的任何断点.

脚本:

function updateServiceInfo(nodeId) {
        var id = { id: nodeId };
        $.ajax({
            url: '/ServiceInfo/ServiceInfoPartial',
            type: 'GET',
            data: id,
            dataType: 'html',
            success: function (data) {
                $('#serviceInfoContent').html(data);
            },
    error: function (request, error) {

    }
        });
    }
Run Code Online (Sandbox Code Playgroud)

控制器:

 public class ServiceInfoController : Controller
    {
        public ActionResult ServiceInfo()
        {
            return PartialView("ServiceInfo");
        }

        public ActionResult ServiceInfoPartial(string id)
        {
            return PartialView("ServiceInfoPartial");
        }
    }
Run Code Online (Sandbox Code Playgroud)

浏览次数:

serviceinfopartial

@model string
<p>
    ????? ?????</p>
Run Code Online (Sandbox Code Playgroud)

serviceinfo

<div id="serviceInfo">
    <div id="ContainerPanel" class="ContainerPanel">
        <div id="serviceInfoHeader" class="collapsePanelHeader">
            <div id="dvHeaderText" class="HeaderContent">
                ???? ???????</div>
            <div id="dvArrow" class="ArrowClose">
            </div>
        </div>
        <div id="serviceInfoContent" class="serviceInfoContent">

        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

控制台中返回的响应是

GET http://localhost/Managers/GetManagers?nodeId=563344 404 Not Found 42ms
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 12

Ahhhhhhhhhhhhhh,另一个硬编码的网址:

url: '/ServiceInfo/ServiceInfoPartial',
Run Code Online (Sandbox Code Playgroud)

永远不要在ASP.NET MVC应用程序中硬编码这样的URL.

始终使用url帮助程序生成它们:

url: '@Url.Action("ServiceInfoPartial", "ServiceInfo")',
Run Code Online (Sandbox Code Playgroud)

或者如果这是在一个单独的javascript文件中,你不能使用url helper,只需在某些DOM元素上使用HTML5 data-*属性:

<div id="serviceInfo" data-url="@Url.Action("ServiceInfoPartial", "ServiceInfo")">
...
</div>
Run Code Online (Sandbox Code Playgroud)

然后在你的JavaScript中简单地说:

url: $('#serviceInfo').data('url'),
Run Code Online (Sandbox Code Playgroud)

您在IIS中托管代码时代码不起作用的原因是因为在IIS中您可能正在将应用程序托管在虚拟目录中,因此正确的URL不再/ServiceInfo/ServiceInfoPartial/YourAppName/ServiceInfo/ServiceInfoPartial.这就是为什么你永远不应该硬编码任何网址并使用帮助程序来生成它们的原因=>这是因为帮助者处理这种情况.使用帮助程序的另一个好处是,如果您以后决定更改路径的布局,Global.asax则无需修改所有javascript文件等...您的URL管理集中在一个位置.