调用web api操作时,Jquery Ajax抛出错误

时间:2018-05-26 09:02:40

标签: jquery ajax asp.net-web-api

这是我用来调用web api动作的jquery ajax代码。

var baseurl = 'http://localhost:58782/api/Appointments/UserAppointments/tridip@gmail.com/'

$.ajax({
url: baseurl,
type: 'GET',
dataType: 'json',
success: function (data, textStatus, xhr) {
    console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
    console.log(textStatus);
}

}).done(function () {


});

这是我的网络API代码,IEnumerable<Entities.UserAppointments>

返回System.Net.Http.HttpResponseMessage

完整的网络API代码。它经过测试和运行。我猜错误是在jquery ajax代码中。

[System.Web.Http.HttpGet, System.Web.Http.Route("UserAppointments/{email}")]
public System.Net.Http.HttpResponseMessage UserAppointments(string email = null)
{
    System.Net.Http.HttpResponseMessage retObject = null;

    if (!string.IsNullOrEmpty(email))
    {
        UserAppointmentService _appservice = new UserAppointmentService();
        IEnumerable<Entities.UserAppointments> app = _appservice.GetAllUserAppointments(email);

        if (app.Count() <= 0)
        {
            var message = string.Format("No appointment found for the user [{0}]", email);
            HttpError err = new HttpError(message);
            retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
            retObject.ReasonPhrase = message;
        }
        else
        {
            retObject = Request.CreateResponse(System.Net.HttpStatusCode.OK, app);
        }
    }
    else
    {
        var message = string.Format("No email provided");
        HttpError err = new HttpError(message);
        retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
        retObject.ReasonPhrase = message;

    }
    return retObject;
}

public class UserAppointments
{
    public int ID { get; set; }
    public string DoctorName { get; set; }
    public string AvailableDate { get; set; }
    public string AvailableTime { get; set; }
    public string Email { get; set; }
}

我的目标是通过jquery捕获IEnumerable<Entities.UserAppointments>并迭代数据并动态地将这些数据附加到表中。

请指导我怎么做。感谢

1 个答案:

答案 0 :(得分:0)

使用%40表示@。 如在

var baseurl = 'http://localhost:58782/api/Appointments/UserAppointments/tridip@gmail.com/'

应该是

var baseurl = 'http://localhost:58782/api/Appointments/UserAppointments/tridip%40gmail.com/'

请参阅:https://www.w3schools.com/jsref/jsref_encodeURI.asp