c# - Ajax 似乎在 ASP.NET Core 中不起作用
问题描述
我想在 ASP.NET Core 中使用 Ajax,但请求没有转到控制器。我使用 VS 2017 和 ASP.NET Core 2.1。
看法:
<script src="https://ajax.googleapis.com/ajax/libs/d3js/5.7.0/d3.min.js"></script>
<script>
$(document).ready(function () {
$('#buttonDemo1').click(function () {
$.ajax({
type: 'GET',
url: '/demo/demo1',
success: function (result) {
$('#result1').html(result);
}
});
});
})
</script>
<fieldset>
<legend>
<form>
<input type="button" value="demo1" id="buttonDemo1" />
<br />
<span id="result1">
</span>
</form>
</legend>
</fieldset>
控制器:
[Route("Demo1")]
public IActionResult Demo1()
{
return new JsonResult("DEmo1");
}
启动.cs:
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
更新:我测试了这段代码,它在我的项目中工作:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/Demo/demo1", true);
xhttp.send();
}
</script>
感谢帮助
解决方案
相对 URL 可能存在问题:我将使用 c# 中的 URL Action Helper 生成 URL 在您看来:
<script>
$(document).ready(function () {
var url = '@Url.Action("Demo1", "Demo")';
$('#buttonDemo1').click(function () {
$.ajax({
type: 'GET',
url: url,
success: function (result) {
$('#result1').html(result);
}
});
});
});
</script>
推荐阅读
- javascript - Cloudflare Worker TypeError:一次性使用主体
- javascript - react-webcam(npm 包)视频大小
- sharepoint - SPOnline:在我的 SPfx WebPart 中包含功能/资产部署后,我无法将其放在任何 SitePage 上
- c++ - SFINAE 适用于扣除但因替代而失败
- c - Pointer and printf()
- c++ - 找不到文件“SDL.h”,但程序编译
- go - golang 与 protobuf 与 dep
- c++ - 如何在应用程序中将 com.apple.security.smartcard 权利设置为是
- python - 如何用 sin cos 和 pi 绘制一个圆
- python - 使用 pyinstaller 的自定义图标不起作用