我正在尝试通过AJAX调用向我的localhost发送GET请求并返回promise对象,然后使用它。 (数据来自功能Web服务调用)。我将以下内容添加到我的web.config文件中,似乎是“no get request allowed”错误:
<system.web>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
JS
$(document).ready(function () {
function fetch() {
var data = { firstName: 'd' };
return $.ajax({
url: "../../Service.asmx/GetPersonsByName",
data: JSON.stringify(data),
dataType: "json",
success: function (results) {
console.log(results.d);
},
error: function (xhr, ajaxOptions) {
console.log(xhr);
console.log(ajaxOptions);
}
});
};
fetch().done(function () {
console.log('finished');
}).fail(function () {
//fails
console.log('fails :(');
});
});
使用此代码,我得到的错误是缺少参数。良好衡量的Web服务方法:
[WebMethod]
[ScriptMethod]
public List<Person> GetPersonsByName(string firstName)
{
var personList = new List<Person>();
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spGetPersonsByName", con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@firstName", firstName);
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Person p = new Person();
p.PersonId = Convert.ToInt32(rdr["PersonId"]);
p.FirstName = rdr["FirstName"].ToString();
p.LastName = rdr["LastName"].ToString();
personList.Add(p);
}
}
}
return personList;
}
Web服务有效,所以我非常确定是错误的Web服务的URL:
GET http://localhost:58268/Service.asmx/GetPersonsByName?{%22firstName%22:%22d%22} 500 (Internal Server Error)
。
编辑:我使用的存储过程有效。
我尝试将$ .param(数据)附加到URL,但也没有用。让这个工作的最佳方法是什么?我应该将我想要的数据附加到URL吗?我需要将它包含在AJAX对象中吗?我尝试了各种不成功的各种事情,我正在寻找这个我没有正确实现的首要主题。