0

The ajax post hits the server and delivers the correct information, but even though it works it still is hitting the error function. The ready state is 0, so it says it isn't even making the request.

            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);

                }
            });

The error message is:Error Msg

My controller looks like this:

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

2 回答 2

0

您的 ajax post 方法或控制器中存在错误。如果您保持 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);

        }
    });

希望这可以帮助。

于 2013-07-11T19:57:56.277 回答
0

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

答案来源 - jQuery:为什么 $.post 执行 GET 而不是 POST

于 2013-07-12T21:32:56.170 回答