[英]how to correctly call my rest api from ajax javascript Client
我有一个REST API,我想从我的ajax javascript客户端调用它。
我打了电话,没有任何反应。 我的移动浏览器仅显示“忙”。
没有错误返回。
这是我的代码背后:
[HttpPost]
[Route("Services/Image/Validate")]
public byte Validate(string KeyCode)
{
return 1;
}
这是我的JavaScript客户端:
$("#btnValidate").click(function () {
try {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
fail: function (a) {
$("#error").html(objRequest);
}
});
}
catch (ex)
{
$("#error").html(ex);
}
return false;
});
仅当HTTP请求失败时,catch函数才会引发错误。 为了了解服务器端代码中的错误,您需要在ajax请求中使用error
函数,
您还提到浏览器不执行任何操作,这可能是由于
$ is not defined
检查控制台) 如果您的服务器端代码在其他域中,请启用CORS
$("#btnValidate").click(function () { var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate"; $.ajax({ type: 'POST', url: url, data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }', contentType: 'application/json; charset=utf-8', dataType: 'json', success: function (msg) { $('#divStep1').hide(); $('#divStep2').show(); }, error: function (e) { console.log(e.responseText); //Acutal error console.log(e); //Get the entire error details } }); });
您发送到$.Ajax()
的设置对象不希望使用fail
参数。 也许您混淆了诺言?
无论如何,可能应该是error
。
例如。
$("#btnValidate").click(function () {
try {
var url = "http://MY_DOMAIN_NAME/api/Services/Image/Validate";
$.ajax({
type: 'POST',
url: url,
data: '{ "KeyCode" : "' + $("#KeyCode").val() + '" }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
$('#divStep1').hide();
$('#divStep2').show();
},
error: function ( jqXHR, textStatus, errorThrown) {
$("#error").html(textStatus);
}
});
}
catch (ex)
{
$("#error").html(ex);
}
return false;
});
另外,我不确定您是否应该将data
属性作为字符串,但是也许这就是您想要的方式。
关于此的所有文档在这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.