後端回傳字串給前端
1.建立後端aspx
2.建立前端html (ajax呼叫aspx)
#ASPX
新增專案
新增aspx
把html都刪掉,只留
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm3.aspx.cs" Inherits="WebApplication2.aspx.WebForm1" %>
.cs的部分
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("hihi");
Response.End();
}
#ajax
新增html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="../js/jquery-3.2.1.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div id="result"></div>
<script>
$(document).ready(function () {
$.ajax({
url: "WebForm1.aspx",
type: 'POST',
success: function (data) {
$('#result').text(data);
},
error: function (err) {
console.log("err:");
console.log(err);
alert(err);
}
});
});
</script>
</body>
</html>
#測試
html 右鍵 在瀏覽器中檢視
進階
將js由html抽離開來
#js
$(document).ready(function () {
$.ajax({
url: "WebForm1.aspx",
type: 'POST',
success: function (data) {
$('#result').text(data);
},
error: function (err) {
console.log("err:");
console.log(err);
alert(err);
}
});
});
#html
匯入js
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="../js/jquery-3.2.1.js" type="text/javascript"></script>
<script src="js1.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<div id="result"></div>
</body>
</html>
#測試
html 右鍵 在瀏覽器中檢視