2016-09-15 109 views
1

我有一个名为themess的文件Controller类中的函数,我试图通过JQuery AJAX发布信息,但控制器中的事件在调试时未触发。ASP.NET MVC JQuery Ajax函数没有触发

网址是http://localhost:8081/character/two

是应该被接受和处理代码的功能是: -

public ActionResult themess(string sText) 
    { 
     return Json(new { success = true, message = "Inserted" }, JsonRequestBehavior.AllowGet); 
    } 

当代码似乎被接收后,它似乎是要去功能错误。它转到[httpPost]功能。

当我通过提琴手追查,我得到

POST http://localhost:58281/character/two/themess HTTP/1.1 
Host: localhost:58281 
Connection: keep-alive 
Content-Length: 13 
Accept: application/json, text/javascript, */*; q=0.01 
Origin: http://localhost:58281 
X-Requested-With: XMLHttpRequest 
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36 
Content-Type: application/json; charset=UTF-8 
Referer: http://localhost:58281/character/two 
Accept-Encoding: gzip, deflate 
Accept-Language: en-GB,en-US;q=0.8,en;q=0.6 
Cookie: ASP.NET_SessionId=3vhn5okbsiblowtkt34puxsf;_ga=GA1.1.513197781.1472146597; __atuvc=257%7C34%2C174%7C35%2C699%7C36%2C145%7C37; __atuvs=57dae9e7623c17f3002 

STEXT =消息(这条线连接到上面的跟踪)

我缺少什么,为什么themess不点火,我应该在RouteConfig中加入一些东西,就像我现在所拥有的一切。

routes.MapRoute("CharacterRule", "character/{id}/{Misc}", new { Controller = "file", action = "Index", id = UrlParameter.Optional }); 
routes.MapRoute("CharacterDupRule", "character/{id}", new { Controller = "file", action = "Index", id = UrlParameter.Optional }); 

这是我的jQuery函数提前建议

$("#form1").submit(function (e) { 
    e.preventDefault(); 



    $.ajax({ 
    type: "POST", 
    url: '@("/file/two/themess")', 
    dataType: "json", 
    data: 'sText=Message', 
    contentType: "application/json; charset=utf-8", 
    success: function() { 
     alert('success'); 
    }, 
    failure: function(response) { 
     alert(response.d); 
    } 
    }); 
}); 

感谢。

+0

你想在你的ajax调用中使用'/ character/two/themes'作为你的url吗?因为这就是你说你的网址是为你的网站** http:// localhost:8081/character/two ** – Zack

+0

这将是理想的,我把/ file/two的理由是我读了某处要使用@Url .Action(“postcomment”)以及它的粗略翻译,应该使用URL.Action或/ character/two/themess,我会更正并测试和更新。 – MiscellaneousUser

+0

您传递的数据不是json格式,但是您声明为这样。 –

回答

0

尝试以下

$.ajax({ 
    type: "POST", 
    url: '@Url.Action("themess","file")', // instead of '@("/file/two/themess")', 
    data: {'sText': "Message"}, // instead of 'sText=Message', 
    success: function() { 
     alert('success'); 
    }, 
    failure: function(response) { 
     alert(response.d); 
    } 
    }); 
}); 

的情况下,如果你想多数据发送到动作,你可以在数据发送它们如下:

data: {'paramName1': value1, 'paramName2': value2,...,'paramNameI',valueI} 

希望这将帮助你