AJAX调用不调用MVC方法并返回成功

时间:2017-05-24 16:05:30

标签: jquery ajax asp.net-mvc methods

我正在尝试向位于 DefaultController.cs

中的MVC方法发出AJAX请求
[ 22.]
[ 22.]
[ 22.]
[ 22.00000033]
[ 8.75471707]
[ 4.34171812]
[ 0.81508685]
[-1.16277103]
[-2.42105811]
[-3.17288066]
[-3.61657372]
[-3.85653348]
[-3.96397335]
[-3.99561793]
[-3.99984826]
[-3.99999934]
[-4.]
[-4.]
[-4.]

返回var booking = { price: price, distance: distance } $.ajax({ contentType: "application/json; charset=utf-8", data: JSON.stringify({ booking: booking }), //Turns into: "{\"booking\":{\"price\":\"56.1376\",\"distance\":\"35086\"}}" url: "/Default/submitBooking", cache: false, success: function (data) { alert("success " + data.d) }, error: function (XMLHttpRequest, textStatus, errorThrown) { if (errorThrown != 'abort') debugger; } }) ,并且success undefined方法中没有断点。

submitBooking()

public ActionResult submitBooking(Booking booking) { return Json(new { success = true, message = "Booking success" }, JsonRequestBehavior.AllowGet); } 类:

Booking

1 个答案:

答案 0 :(得分:1)

问题是因为您的Action返回了带有successmessage属性的JSON。然后,您的JS代码尝试从名为d的响应中读取属性,该响应不存在,因此您看到undefined值。

要解决此问题,您只需修改JS代码以从响应中读取正确的属性:

var booking = { price: price, distance: distance }
$.ajax({
  contentType: "application/json; charset=utf-8",
  data: { booking: booking }, // no need to JSON.stringify here, jQuery does it for you
  url: "/Default/submitBooking",
  cache: false,
  success: function (data) {  
    console.log(data.success);
    console.log(data.message);
  },
  error: function (XMLHttpRequest, textStatus, errorThrown) { 
    if (errorThrown != 'abort') 
      debugger; 
  }
})