问题
I am trying to get JSON from my controller to use in jQuery. I have the following code. When I visit the URL in my browser it returns the json so I know that the controller is working... But I get the following
GET http://localhost:52802/Checkout/GetContactById?id=1 net::ERR_INCOMPLETE_CHUNKED_ENCODING
client-side jQuery
var theUrl = window.location.origin + '/Checkout/GetContactById?id=' + contactId;
$.ajax({
url: theUrl,
type: "GET",
success: function (result) {
alert("Success");
},
error: function (error) {
alert("Error");
}
});
Server-side Controller
[HttpGet]
public IActionResult GetContactById(int id)
{
Contact contact = this.checkoutDataAccess.GetContactById(id);
return Json(contact);
}
The only alert I get is "Error"
Update
After more research it looks like everything is loading... but I am getting an error
Failed to load response data
in the console.
I stepped through the code and everything works on the controller side. I am not sure if it is not formatting the JSON correct, or if I am not receiving it correctly. Either way I have no idea what is going on.
回答1:
Actually you are getting the text Error since you put alert("Error"); Try alert(error); instead Or try debugging using firebug
回答2:
Try adding datatype JSON to the ajax call.
And maybe try adding the parameter in the body.
like so:
var theUrl = window.location.origin + '/Checkout/GetContactById';
$.ajax({
url: theUrl,
type: "GET",
dataType: "json",
data: { id: contactId },
success: function (result) {
alert("Success");
},
error: function (error) {
alert("Error");
}
});
And i would suggest using Url.Action helper.
like:
$.ajax({
url: '@Url.Action("GetContactById", "Checkout")',
type: "GET",
dataType: "json",
data: { id: contactId },
success: function (result) {
alert("Success");
},
error: function (error) {
alert("Error");
}
});
回答3:
I had same problem and after looking for several possible solutions, I've tried to consume my api form Postman and discovered that I was returning a bad formed JSON. In my case was because one of properties of my ViewModel was int[] type. After remove this property I could retrieve data normally.
I hope it helps.
来源:https://stackoverflow.com/questions/44467409/trying-to-get-json-from-mvc-controller-and-getting-error-neterr-incomplete-chu