weixin_33713350 2015-08-24 16:58 采纳率: 0%
浏览 123

使用Ajax调用Web Api方法

I wrote a WebApi project that get firstname and lastname as a input parameter and return all the info. I use RestShop to call the webApi and return data. This is working and is returning but for some reason I have to use Ajax call to call the api. I can’t get the Ajax call working. I have used different links in this website but it return me empty data and error. it retuen empty for both alerts: alert(FirstName); and at the end retues [object][object] error.

This is the RestShop that is working:

 public List<Data> GetData(string FirstName, string LastName)
    {
        RestClient _client = new RestClient();
        string _url = "http://localhost:51142";
        _client = new RestClient(_url);


        //DocGen/Documents/GetByFLName/TERRI/TIMMERMAN
        var request = new RestRequest("Gen/Doc/GetByFLName/{FirstName}/{LastName}", Method.GET) { RequestFormat = DataFormat.Json };
        request.AddParameter("FirstName", FirstName, ParameterType.UrlSegment);
        request.AddParameter("LastName", LastName, ParameterType.UrlSegment);

        var response = _client.Execute<List<Data>>(request);
        if (response.Data == null)
            throw new Exception(response.ErrorMessage);

        return response.Data;

    }

This is Ajax code to call same method ans it returns , [object][object] error.

function GetEmployee() {
    jQuery.support.cors = true;
    var FirstName = $('#FirstName').val();
    alert(FirstName);
    var LastName = $('#LastName').val();
    alert(LastName);
    $.ajax({
        url: 'http://localhost:51142/Gen/Doc/GetByFLName/'+ '/' + FirstName + LastName,
        type: 'GET',
        dataType: 'json',
        success: function (data) {
                            alert(data);
        },
        error: function (x, y, z) {
            alert(x + '
' + y + '
' + z);
        }
    });
}

and this is textboxes:

First Name:
   @Html.TextBox("FirstName")

  Last Name:
  @Html.TextBox("LastName")

and this is my method in webApi:

    public IHttpActionResult GetByFLName(string id1, string id2)
    {

        DAL.DataManager dal = new DAL.DataManager();
        CMSIGateway gateway = new CMSIGateway();
        gateway = dal.Get_CM_BY_FLName(id1, id2);


        if (gateway == null)
        {
            return NotFound();
        }

        return Ok(gateway);
    }
  • 写回答

1条回答 默认 最新

  • weixin_33701294 2015-08-25 03:38
    关注

    ur putting incorrect parameter to the url it should be like this

     url: 'http://localhost:51142/Gen/Doc/GetByFLName?id1=' + FirstName + "&id2=" +LastName
    
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料