无法从JQuery获取请求

时间:2015-12-12 12:52:11

标签: javascript jquery api

我有自动完成输入字段,所以我已经完成了一个根据用户请求检索数据的功能。我已经使用webform测试了该函数并且工作正常,但是当我尝试使用api并向控制器发送请求时,控制器没有收到来自JQuery的任何请求?

JQuery的:

$(document).ready(function () {
        $("#auto").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "api/Employee/GetRe",
                    data: "{'term':'" + $("#auto").val() + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
        });
    });

控制器:

[HttpGet]
    public string GetRe(string term) {

        var re = repository.GetCategory(term);

        return re.First();

    }

功能:

 [WebMethod]
    public  string[] GetCategory(string term)
    {
        List<string> retCategory = new List<string>();
        connection();

        string query = string.Format("select FirstName from Employee where FirstName Like '%{0}%'", term);
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                retCategory.Add(reader.GetString(0));
            }
        }
        con.Close();

        return retCategory.ToArray();
    }

    }

并显示此错误

  

“在控制器'Employee'上找不到与之匹配的操作   请求。“}

1 个答案:

答案 0 :(得分:0)

您正在将JSON对象格式化为字符串。

$(document).ready(function () {
        $("#auto").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "api/Employee/GetRe",
                    data: {'term': $("#auto").val()},
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
        });
    });