【问题标题】:Ajax Post Throwing ErrorAjax 投掷错误
【发布时间】:2013-07-11 19:09:12
【问题描述】:

ajax post 访问服务器并提供正确的信息,但即使它工作,它仍然会遇到错误功能。就绪状态为 0,因此它表示它甚至没有发出请求。

            var serviceURL = '/ContactForm/FirstAjax';
            $.ajax({
                type: "POST",
                url: serviceURL,
                data: JSON.stringify(formInfo),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                            alert("Worked");
                        },

                error: function (xhRequest, ErrorText, thrownError) {
                    alert("Failed to process correctly, please try again" + "\n xhRequest: " + xhRequest + "\n" + "ErrorText: " + ErrorText + "\n" + "thrownError: " + thrownError);

                }
            });

错误信息是:

我的控制器如下所示:

    [HttpPost]
    [ActionName("FirstAjax")]
    [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
    public JsonResult FirstAjax(ContactForm contactForm)
    {            
        return Json("works", JsonRequestBehavior.AllowGet);
    }

【问题讨论】:

  • 检查 xhrequest.responseText
  • 它什么也没做。我在控制台中记录了它,但我不确定如何解释它所说的内容。就绪状态 = 0,状态也是如此。

标签: jquery asp.net-mvc http post controller


【解决方案1】:

您的 ajax 发布方法或控制器中存在错误。 如果您保持 ajax 方法不变,您可以将控制器修改为:

[HttpPost]
[ActionName("FirstAjax")]
[OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
public JsonResult FirstAjax()
{            
    var postedData = new StreamReader(Request.InputStream);
    var jsonEncoded = postedData.ReadToEnd(); //String with json
    //Decode your json and do work. 
    return Json("works", JsonRequestBehavior.AllowGet);
}

如果不想更改控制器,则需要将javascript更改为:

var serviceURL = '/ContactForm/FirstAjax';
$.ajax({
        type: "POST",
        url: serviceURL,
        data: { contactForm: JSON.stringify(formInfo) },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () {
                     alert("Worked");
                },
        error: function (xhRequest, ErrorText, thrownError) {
            alert("Failed to process correctly, please try again" + "\n xhRequest: " + xhRequest + "\n" + "ErrorText: " + ErrorText + "\n" + "thrownError: " + thrownError);

        }
    });

希望这会有所帮助。

【讨论】:

【解决方案2】:

我在使用 Fiddler 并意识到它正在做一个 GET 而不是一个帖子 POST。我想出了如何解决它。当我提交表单时,它使用onsubmit="submitForm();" 调用了Javascript。通过提交表单,它在 url 上执行 GET 而不是 POST。我修复了onsubmit="submitForm(); return false"

答案来源-jQuery: why does $.post does a GET instead of a POST

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-28
    • 2018-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多