Javascript Web API Ajax调用不起作用
下面是我调用自定义web api方法的js代码Javascript Web API Ajax调用不起作用,javascript,jquery,asp.net-web-api,Javascript,Jquery,Asp.net Web Api,下面是我调用自定义web api方法的js代码 $.ajax({ url: '/api/AdminAPI/IndustryPost/?industryName='+addNewIndustryName, type: 'Post', cache: false, contentType: 'application/json; charset=utf-8', success: function (respon
$.ajax({
url: '/api/AdminAPI/IndustryPost/?industryName='+addNewIndustryName,
type: 'Post',
cache: false,
contentType: 'application/json; charset=utf-8',
success: function (response) {
// response code.
}
});
这工作正常,但如果我使用“数据”标签发送数据,它就不工作了。像下面这样
$.ajax({
url: '/api/AdminAPI/IndustryPost',
type: 'Post',
cache: false,
contentType: 'application/json; charset=utf-8',
data: { 'industryName': addNewIndustryName },
success: function (response) {
// response code.
}
});
WebApiConfig是config.maphttpAttribute路由()
这是我的api方法
[ActionName("IndustryPost")]
public void AddIndustry(string industryName)
{
//code here
}
使用fiddler进行测试时,第二个代码请求导致404错误。当直接从URL访问web API时,该方法工作良好
答复:
在对这个主题做了R'N'D之后,我知道在webapi参数绑定中有一个问题。因此,我们可以使用[formUri]标记,也可以拥有一个模型类。像这样
公共类行业名称
{
公共字符串Industryname{get;set;}
}
在webapi方法中
公共空白行业邮政(行业名称行业名称)
{
//
}
jquery中不需要任何更改
这篇文章解释了这一切
行下更改
data: { 'industryName': addNewIndustryName }
到
还要确保addNewIndustryName是全局变量且可访问
或者,您可以简单地分配变量而不使用花括号,如下所示
data: 'industryName='+ addNewIndustryName
在这里,您的ajax url中缺少一个引号:
$.ajax({
url: '/api/AdminAPI/IndustryPost/', //<----here put a / slash at the end
type: 'Post',
cache: false,
dataType: 'json', //<-------you can use json
contentType: 'application/json; charset=utf-8',
data: { 'industryName': addNewIndustryName },
success: function (response) {
// response code.
}
});
$.ajax({
url:“/api/AdminAPI/IndustryPost/”,//我的不好,我很快就发布了。但是在我的代码中是正确的。好吧!尝试用这个url:“/api/AdminAPI/IndustryPost/”,
来更改你的url,
最后添加一个/
。控制台中有任何错误吗?…你能像在用ajax发送数据对象之前所说的那样共享JSFIDLE吗,因此,您可以检查jquery ajax callYes是否可以访问addNewIndustryName对象吗?是的,它是可访问的…在ajax正文中,我使用了firebug并警告消息本身进行确认。未找到与请求URI“”匹配的HTTP资源。这是错误函数中显示的消息。请参阅本文,可能对您有用我对asp.net不太了解:(
data: 'industryName='+ addNewIndustryName
$.ajax({
url: '/api/AdminAPI/IndustryPost/', //<----here put a / slash at the end
type: 'Post',
cache: false,
dataType: 'json', //<-------you can use json
contentType: 'application/json; charset=utf-8',
data: { 'industryName': addNewIndustryName },
success: function (response) {
// response code.
}
});