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
    
    评论

报告相同问题?

悬赏问题

  • ¥15 虚拟机打包apk出现错误
  • ¥30 最小化遗憾贪心算法上界
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝