最近我遇到了将JSON响应返回给基于PHP和JQuery的url的问题。我使用post请求:
$(document).ready(function() {
(function(){
console.log("ran");
$.ajax({
type: "GET",
url: "https://chad-test4.clas.university.edu/Employees/Edit/22",
dataType: "json",
success: function (data) {
console.log("Response recieved");
console.log("Success: " + data);
empData = data;
},
error: function() {
console.log("Failed");
}
});
})();
});
我的控制器是:
public JsonResult Edit(int? id)
{
if (id == null)
{
return Json("Error: Id does not exist", JsonRequestBehavior.AllowGet);
}
employee chad = db.employees.Find(1);
if (chad == null)
{
return Json("Error: employee does not exist", JsonRequestBehavior.AllowGet);
}
chad.last_name = "Changed";
chad.netid = "1111111";
db.Entry(chad).State = EntityState.Modified;
db.SaveChanges();
Console.WriteLine("Successfully gotten");
return Json(chad, JsonRequestBehavior.AllowGet);
}
这样可以保留返回完整的HTML页面,也可以使用以下控制台日志返回错误:
Uncaught TypeError: $(...).alert is not a function(anonymous function)
@misc.js:633
display:410 ran
misc.js:783 Uncaught TypeError: Cannot read property 'elements' of
undefinedcalculateTotalPurposesAmount @ misc.js:783window.onload
@misc.js:627
display:421 Failed
我是否需要创建一个Web API项目,以便只返回JQuery数据?