【发布时间】:2016-02-08 08:58:38
【问题描述】:
我写了简单的 webapi 方法。我正在尝试使用 ajax 调用在 mvc 中访问该方法。我在 browser 和 fiddler 中得到输出。但它在 cshtml 页面中不起作用。如果我必须添加一些内容,请告诉我。 请看这个..
function validate() {
alert("came");
$.ajax({
url: 'http://localhost:54544/api/home/getname/',
method: 'GET',
contentType: 'application/form-url-encoded',
success: function ()
{
alert("success");
},
error: function (ex) {
alert(ex.responseText);
}
});
}
在这里查看html代码
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>View</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script type="text/javascript">
// beforeSend: function(xhr, settings) { xhr.setRequestBody('Authorization','Bearer ' + token); } ,
$(document).ready(function () {
alert("came");
$.ajax({
url: "http://localhost:54544/api/home/getname/",
type: "Get",
success: function (data) {
alert("test came");
},
error: function (msg) { alert("error"); alert(msg); }
});
});
</script>
</head>
<body>
<div>
<table>
<tbody>
<tr>
<td><input type="button" value="Submit" onclick="validate()" name="Submit" /> </td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
【问题讨论】:
-
我尝试删除内容类型。但它不起作用。
-
您的浏览器控制台有错误吗?发布您完整的
cshtml和Layout页面,您是否将其包装在部分中?因为在默认模板下,如果您立即在cshtml中调用<script></script>而不将其包装在部分中,它将在jquery.js之前调用,并且会导致错误,因为jquery.js在RenderBody()之后被调用Layout页面 -
添加了 cshtml。请检查一次并在控制台中出错:XMLHttpRequest 无法加载 localhost:54544/api/home/getname。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'localhost:57842'。
标签: jquery ajax asp.net-mvc asp.net-mvc-4 model-view-controller