8

我有这个 jquery post call,它以某种方式调用错误函数,即使它将数据输入数据库非常好。

<script type="text/javascript">
    $(document).ready(function () {
        $("#ExtMailCreate").click(function () {
            var url = '@Url.Action("Create")';
            var data = JSON.stringify(SaveExternalMail());
            $.ajax({
                type: "POST",
                url: url,
                data: data,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    $("#result").append("pass");
                },
                error: function (data) {
                    $("#result").append("error");
                }
            });
        });
    });

    function SaveExternalMail() {
        var costcentrecode = $("#CostCentreCode").val();
        var day = $("#ExtMailDatePicker").val();
        var externalMailItemID = $("#ExternalMailItemID").val();
        var externalMailLocationID = $("#ExternalMailLocationID").val();
        var quantity = $("#Quantity").val();
        return {
            CostCentreCode: costcentrecode,
            Day: day,
            ExternalMailItemID: externalMailItemID,
            ExternalMailLocationID: externalMailLocationID,
            Quantity: quantity
        };
    }
</script>

- 控制器

   <HttpPost()> _
    Function Create(ByVal collection As ExternalMail) As JsonResult
        Try
            If ModelState.IsValid Then
                _repositoryForExternalMail.Save(collection, "")
            End If

            Return Json(New ExternalMail With {.CostCentreCode = collection.CostCentreCode, .Day = collection.Day, .Quantity = collection.Quantity}, JsonRequestBehavior.AllowGet)

        Catch ex As Exception
            Return Json("An Error Occurred")
        End Try
    End Function

- - 更新 - -

谷歌浏览器报告以下错误:

POST localhost/Mail/ExternalMail/Create 403 (Forbidden)
jquery.min.js:4 send jquery.min.js:4 f.extend.ajax
jquery.min.js:4 (匿名函数) Create:59 f.event。调度
jquery.min.js:3 h.handle.i

-- 页面来源

 <!DOCTYPE html>
 <html>
 <head>
<meta charset="utf-8" />
<title>Create</title>
<link href="/Mail/Content/Site.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="/Mail/Scripts/jqModal.css" />
<link href="http://cdn.kendostatic.com/2012.2.913/styles/kendo.common.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.2.913/styles/kendo.dataviz.min.css" rel="stylesheet" type="text/css" />
<link href="http://cdn.kendostatic.com/2012.2.913/styles/kendo.blueopal.min.css" rel="stylesheet" type="text/css" />

     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">  </script>
 <script src="/Mail/Scripts/json2min.js" type="text/javascript"></script>
 <script src="/Mail/Scripts/jquery.JSONP.min.js" type="text/javascript"></script>
 <script src="/Mail/Scripts/jquery.validate.min.js" type="text/javascript"></script>
 <script src="/Mail/Scripts/jquery.validate.unobtrusive.min.js" type="text/javascript">         </script>

<script src="http://cdn.kendostatic.com/2012.2.913/js/kendo.all.min.js" type="text/javascript"></script>
<script src="http://cdn.kendostatic.com/2012.2.913/js/kendo.aspnetmvc.min.js" type="text/javascript"></script>
<script src="/Mail/Scripts/modernizr-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript" src="/Mail/Scripts/jqModal.js"></script>

 </head>
 <body>
<div class="page">
    <header>
  <div id="pageheader">
        <div id="pageheader_left">
            <img id="TitleBanner" src=/Mail/Content/Images/titlebanner.jpg alt="TitleBanner"/>
        </div>
        <div id="pageheader_center">

        </div>
        <div id="pageheader_right">
         <a href="/Mail/" title="Click to go to Home Page"><img id="HomeImage" src=/Mail/Content/Images/home.gif alt="Home"/></a>
         <a href="/Mail/Account/About"><img id="AboutImage" src=/Mail/Content/Images/about.gif alt="About"/></a>
          <a href="/Mail/Account/Logoff"><img id="ExitImage" src=/Mail/Content/Images/logoff.gif alt="Exit"/></a>
         </div>    
        <div id="pageheader_lower">
        </div>    
    </div>


     <ul class="k-widget k-reset k-header k-menu" id="Menu"><li class="k-item k-state-default">
 <a class="k-link" href="/Mail/">Home</a></li><li class="k-item k-state-default"><span class="k-link">Manage<span class="k-icon k-i-arrow-s"></span></span><ul class="k-group"><li class="k-item k-state-default"><span class="k-link">External Mail<span class="k-icon k-i-arrow-e"></span></span><ul class="k-group"><li class="k-item k-state-default"><a class="k-link" href="/Mail/ExternalMail">External Mail</a></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/ExternalMailCategory">External Mail Category</a></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/ExternalMailItem">External Mail Item</a></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/ExternalMailCost">External Mail Cost</a></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/ExternalMailLocation">External Mail Location</a></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/ExternalMailInvoice">External Mail Invoice</a></li></ul></li><li class="k-item k-state-default"><span class="k-link">Internal Mail<span class="k-icon k-i-arrow-e"></span></span><ul class="k-group"><li class="k-item k-state-default"><a class="k-link" href="/Mail/InternalMail">Internal Mail</a></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/InternalMailCategory">Internal Mail Category</a></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/InternalMailItem">Internal Mail Item</a></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/InternalMailCost">Internal Mail Cost</a></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/InternalMailLocation">Internal Mail Location</a></li></ul></li><li class="k-item k-state-default"><a class="k-link" href="/Mail/CostCentre">Cost Centre</a></li></ul></li><li class="k-item k-state-default"><span class="k-link">Reports</span></li></ul><script>
jQuery(function(){jQuery("#Menu").kendoMenu({});});
 </script>              
    </header>
    <section id="main">

 <div class="jqmWindow" id="dialog">
     <a href="#" class="jqmClose">Close</a>
 </div>


 <script type="text/javascript">

$(document).ready(function () {

    var exturl = '/Mail/ExternalMail/Create';
    $("#ExtMailCreate").click(function () {


        var dataJSON = JSON.stringify(SaveExternalMail());

        $.ajax({
                    cache: false,
                        type: "POST",
                        url: exturl,
                        data: dataJSON,
                        contentType: 'application/json; charset=utf-8',
                        success: function (data) {
                            showMessage("test", "information");
                        },
                        error: function (xhr, textStatus, errorThrown) {
                            showMessage("An error occurred while adding this record.           Please try again later.", "error");
                        }


                    });

    });

});

function showMessage(message, messageType) {
    $().ready(function () {
        $('#dialog').jqm();

        switch (messageType) {
            case 'information':
                $('#dialog').removeClass("errorMessage");
                $('#dialog').addClass("informationMessage");
                break;
            case 'error':
                $('#dialog').removeClass("informationMessage");
                $('#dialog').addClass("errorMessage");
                break;
            default:
                break;
        }

        $('#dialog').html("<a href=\"#\" class=\"jqmClose\">Close</a><br />" + message);
        $('#dialog').jqmShow();
    });
}


    function SaveExternalMail() {
        var costcentrecode = $("#CostCentreCode").val();
        var day = $("#ExtMailDatePicker").val();
        var externalMailItemID = $("#ExternalMailItemID").val();
        var externalMailLocationID = $("#ExternalMailLocationID").val();
        var quantity = $("#Quantity").val();

        return { CostCentreCode: costcentrecode, Day: day, ExternalMailItemID:      externalMailItemID, ExternalMailLocationID: externalMailLocationID, Quantity: quantity };
    }

 </script>
 <form action="/Mail/ExternalMail/Create" method="post">    <fieldset>
    <legend>ExternalMail</legend>
    <div class="editor-label">
        <label for="ExternalMailLocationID">Please select a Location</label>
    </div>
    <div class="editor-field">
        <select data-val="true" data-val-number="The field ExternalMailLocationID must be a number." data-val-required="The ExternalMailLocationID field is required." id="ExternalMailLocationID" name="ExternalMailLocationID">
 <option value="2">Sydney</option>
 </select>
        <span class="field-validation-valid" data-valmsg-for="ExternalMailLocationID" data-valmsg-replace="true"></span>
    </div>
    <div class="editor-label">
        <label for="CostCentreCode">Please select a CostCentre</label>
    </div>
    <div class="editor-field">
        <select id="CostCentreCode" name="CostCentreCode" size="15"><option value="Test000">Test</option>
      </select>
        <span class="field-validation-valid" data-valmsg-for="CostCentreCode" data-valmsg-replace="true"></span>
    </div>
         <div class="editor-label">
             <label for="ExternalMailItemID">Please select a Mail Item Type</label>
         </div>
         <div class="editor-field">
             <select data-val="true" data-val-number="The field ExternalMailItemID must be a number." data-val-required="The ExternalMailItemID field is required." id="ExternalMailItemID" name="ExternalMailItemID"><option value="4">Test10</option>
      </select>
        <span class="field-validation-valid" data-valmsg-for="ExternalMailItemID" data-valmsg-replace="true"></span>
    </div>
    <div class="editor-label">
        <label for="Day">Please select a Date</label>
    </div>
    <div class="editor-field">
        <input class="k-input" id="ExtMailDatePicker" name="ExtMailDatePicker" type="date" value="19/03/2013" /><script>
     jQuery(function(){jQuery("#ExtMailDatePicker").kendoDatePicker({"format":"d/MM/yyyy","min":new Date(1900,0,1,0,0,0,0),"max":new Date(2099,11,31,0,0,0,0)});});
      </script>
        <span class="field-validation-valid" data-valmsg-for="Day" data-valmsg-replace="true"></span>
    </div>
    <div class="editor-label">
        <label for="Quantity">Please enter the no of Mails</label>
    </div>
    <div class="editor-field">
        <input class="text-box single-line" data-val="true" data-val-number="The field Quantity must be a number." data-val-required="The Quantity field is required." id="Quantity" name="Quantity" type="text" value="" />
        <span class="field-validation-valid" data-valmsg-for="Quantity" data-valmsg-replace="true"></span>
    </div>
    <p>
        <input type="button" value="Create" id="ExtMailCreate" />
    </p>
</fieldset>
 </form><div>
<a href="/Mail/ExternalMail">Back to List</a>
 </div>
      <div id="result">
 </div>

    </section>
    <footer>

    </footer>
</div>
 </body>
 </html>

-- Ajax 请求响应

Request URL:http://localhost/Mail/ExternalMail/Create
Request Method:POST
Status Code:403 Forbidden
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Authorization:Negotiate    TlRMTVNTUAADAAAAAAAAAEgAAAAAAAAASAAAAAAAAABIAAAAAAAAAEgAAAAAAAAASAAAAAAAAABIAAAABcKIogUBKAoAAAAP
Connection:keep-alive
Content-Length:113
Content-Type:application/json; charset=UTF-8
Cookie:ASP.NET_SessionId=tg1xrabaigumj3fxooa1satc
DNT:1
Host:localhost
Origin:http://localhost
Referer:http://localhost/Mail/externalmail/Create
User-Agent:Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko)     Chrome/25.0.1364.172 Safari/537.22
X-Requested-With:XMLHttpRequest
Request Payload
{"CostCentreCode":"B125","Day":"20/03/2013","ExternalMailItemID":"4","ExternalMailLocationID":"1","Quantity":"2"}
Response Headersview source
Cache-Control:private, s-maxage=0
Content-Length:127
Content-Type:application/json; charset=utf-8
Date:Wed, 20 Mar 2013 01:31:21 GMT
Server:Microsoft-IIS/5.1
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
X-Powered-By:ASP.NET
4

4 回答 4

2

我认为问题在于指定JsonRequestBehavior.AllowGet

然后发布到方法:

$.ajax({
  type: "POST",
  url: url,

如果数据库正在填充,我们知道存储库代码正在触发。浏览器报告一个 HTTP403,闻起来像是框架抛出了一个安全异常,如果它期望响应 GET 并接收 POST,它可能会这样做。

于 2013-03-19T01:45:00.043 回答
0

如果您指定数据类型为 json 但无法将响应解析为 json,则 ajax 请求将进入错误块。

打开chrome并在错误块中放置一个断点并查看数据的值。将内容放在 json 验证器中并检查以确保您的响应是有效的 json。

还将成功和错误函数的方法标志更改为

success: function(data, txtStatus, jqxhr){ // code here }
error: function( jqxhr, txtStatus, errorThrown) { // code here }

然后在这些功能中放置断点,您可以检查参数并更清楚地查看发生了什么。

--更新由于您收到403错误代码,请在stackoverflow上查看此答案并检查您指向的文件夹的权限

发布 asp.net MVC 后禁止 403

也看看这个,因为你正在运行 IIS 5.1 它看起来像......它可能是相似的

在 IIS 5.2 上运行 MVC2 应用程序

于 2013-03-19T20:29:41.337 回答
0

尝试将控制器中的方法从 JsonResult 更改为 ActionResult

 <HttpPost()> _
    Function Create(ByVal collection As ExternalMail) As ActionResult
于 2013-03-19T20:55:45.873 回答
0

正如 denas 所说,您需要检查返回的 textStatus 和 errorThrown 生成的变量中的内容,因为您可以返回 200 HTTP 代码以外的其他内容,并且您的代码仍然可以正常执行(因为您报告您的记录被添加到数据库)。一个 200 HTTP 代码将触发“成功”功能,我现在不记得了,但 4xx 或 5xx 中的某些内容应该会触发“错误”功能。

这里要考虑的主要是网络服务器的 HTTP 返回代码控制在 jquery ajax 调用中触发什么函数

将您的代码更改为:

error: function( jqXHR, textStatus, errorThrown ) {
    console.log(textStatus);
    console.log(errorThrown);
}

并告诉我们你在这些 textStatus 和 errorThrown 变量中有什么。

于 2013-03-21T19:50:42.477 回答