我正在尝试执行一个简单的Ajax调用来从HTML页面注册用户,MVC 4中的函数被调用并且运行良好,但它返回的内容永远不会触发Ajax调用中的“success”函数。
如果我使用我的浏览器手动访问Register()函数,它运行良好并返回我想要的消息,但不是通过Ajax
function register() {
var userModel = {
phoneNumber: "1236663",
displayname: "yasuuu",
}
$.ajax({
type: "POST",
url: "http://localhost:13234/home/register",
data: userModel,
success: function (response) {
$('#deleteThisDivButNotItsContent').html(response)
}
})
}
public ActionResult Register(string PhoneNumber, string DisplayName)
{
// Some working code here ...
ViewBag.Message = "Some Message"; // just trying to display simple text
return View();
/* tried all of the lines below too */
//return this.Json("1234");
//return Json("{ result : true }");
//return PartialView("ShowResultPartial", JsonRequestBehavior.AllowGet);
//CommentSection commentSection = new CommentSection();
//return PartialView("CommentSection");
//return PartialView("CommentSection", commentSection);
//return Json(new { success = true, response = "Saved ok" });
}
我正在使用JQuery 2.0.3
答案 0 :(得分:0)
你为什么不尝试这个?
function register() {
$.post("/home/Register",
{phoneNumber: "1236663", displayname: "yasuuu"},
function(data,status,xhr){
$('#deleteThisDivButNotItsContent').html(data.response);
});
}
在控制器中
return Json(new { success = true, response = "Saved ok" });
答案 1 :(得分:0)
让它返回JsonResult
而不是ActionResult
。 AJAX如何解释ActionResult视图?
另外,您将对象发送到Register()方法,但是您正在接收两个字符串变量。
以下是一个例子:
function register() {
var userModel = {
phoneNumber: "1236663",
displayName: "yasuuu",
}
$.ajax({
type: "POST",
url: "http://localhost:13234/Home/Register",
data: userModel,
success: function (response) {
$('#deleteThisDivButNotItsContent').html(response.message)
}
});
}
publi class UserModel
{
public string phoneNumber { get; set; }
public string displayName { get; set; }
}
public JsonResult Register(UserModel userModel)
{
// Some working code here ...
return Json(new { message = "Some message here" }, JsonRequestBehavior.AllowGet);
}
答案 2 :(得分:0)
当您在浏览器中输入http://localhost:1234/register
时,它会针对该网址发出GET
请求。在您的javascript中,jquery发出POST
请求。 ajax请求收到404错误,因为路由未配置为响应POST
请求。