实例一:
function btnPSetUnityDB(UId, UTrunName, UTimeLeng, UScore) { var xixn = JSON.stringify({ Id: UId, TrunName: UTrunName, TimeLeng: UTimeLeng, Score: UScore }); var xhr = new XMLHttpRequest;//创建一个 XMLHttpRequest 对象,XMLHttpRequest是实现ajax的基础 xhr.open("POST", "/Home/SetTrain", 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; document.getElementById("xinxi").innerHTML = JSON.parse(s).result; } } }
后台
1 [HttpPost] 2 [ValidateAntiForgeryToken] 3 public IActionResult SetTrain([FromBody]UTrainDetails model) 4 { 5 if (model != null) 6 { 7 string ID = model.Id.ToString(); 8 string TrunName = model.TrunName; 9 string TimeLeng = model.TimeLeng.ToString(); 10 string Score = model.Score.ToString(); 11 12 return Json(new { result = ID + "," + TrunName + "," + TimeLeng + "," + Score }); 13 } 14 else 15 { 16 return Json(new { result = "Is Null" }); 17 } 18 }