mvc 处理json数据:
@{
ViewData["Title"] = "Home Page";
}
<div>
<button id="sumbit" onclick="ajax()">获取</button>
<a id="xinxi"></a><br />
姓名:
<input type="text" id="name" />
♠
密码:
<input type="text" id="password" />
jieguo:
<input type="text" id="xinxi22" />
<div id="xinxi" >33333333333 </div>
</div>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" >
function ajax() {
var password = document.getElementById("password").value;
var name = document.getElementById("name").value;
var xixn = JSON.stringify({
Name: name,
Password: password
});
var xhr = new XMLHttpRequest;//创建一个 XMLHttpRequest 对象,XMLHttpRequest是实现ajax的基础
xhr.open("POST", "/Hello/Login", true);//请求方式为"Post","/Home/Index"为服务器地址(在MVC这里就是控制器地址+方法名),true表示选择异步
xhr.setRequestHeader("Content-type", "application/json");//设置请求参数类型
xhr.send(xixn);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var s = xhr.responseText;
alert(s);
document.getElementById("xinxi").innerHTML = JSON.parse(s).result;
} else {
alert(xhr.status + ":" + xhr.readyState+ ":" + xhr.responseText);
}
}
}
</script>
后台代码:
[HttpPost]
public IActionResult Login([FromBody] Model7 model)
{
if (model != null)
{
string Name = model.Name;
string password = model.Password;
return Json(new { result = "my:" + Name + "is:" + password });
}
else
{
return Json(new { result = "it Is Null" });
}
}
public class Model7
{
public string Name { get; set; }
public string Password { get; set; }
}