Ajax (Asynchronous JavaScript and XML) 是一种在不重新加载整个页面的情况下与服务器交换数据并更新部分网页的技术。JSON (JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写,也易于机器解析和生成。
// 使用原生JavaScript
function sendDataToServer() {
const data = {
name: "John Doe",
age: 30,
email: "john@example.com"
};
const xhr = new XMLHttpRequest();
xhr.open("POST", "/api/yourEndpoint", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
console.log("Response:", xhr.responseText);
}
};
xhr.send(JSON.stringify(data));
}
// 使用jQuery
function sendDataWithJQuery() {
const data = {
name: "Jane Smith",
age: 25,
email: "jane@example.com"
};
$.ajax({
url: "/api/yourEndpoint",
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
success: function(response) {
console.log("Success:", response);
},
error: function(xhr, status, error) {
console.error("Error:", error);
}
});
}
[HttpPost]
public ActionResult ReceiveData([FromBody] YourModel model)
{
if (model == null)
{
return BadRequest("Invalid data");
}
// 处理数据
Console.WriteLine($"Received: {model.Name}, {model.Age}, {model.Email}");
return Json(new { success = true, message = "Data received" });
}
[HttpPost]
[Route("api/yourEndpoint")]
public IHttpActionResult Post([FromBody] YourModel model)
{
if (model == null)
{
return BadRequest("Invalid data");
}
// 处理数据
Debug.WriteLine($"Received: {model.Name}, {model.Age}, {model.Email}");
return Ok(new { success = true, message = "Data received" });
}
public class YourModel
{
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
原因: 服务器未正确设置接收JSON数据的请求头。
解决方案:
Content-Type: application/json
[FromBody]
属性原因: JSON数据结构与C#模型不匹配。
解决方案:
原因: 前端和后端不在同一个域下。
解决方案:
// 在WebApiConfig.cs或Startup.cs中
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
// 或在控制器/方法上添加特性
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class YourController : ApiController
{
// ...
}