我需要对返回到ajaxform的json进行操作。我不擅长javascript,无法做到这一点……我可以从controler中的一个方法返回Json,但我能正确地做事情吗?这取决于这个Json结果?
我需要返回状态值,其中状态可以是1,2或2。鉴于此,我需要实现JS,它将向div添加文本,这取决于该脚本从方法中获得的json。一切都应该使用ajax。有人能给我推荐好的教程吗?或者简单地为我编写代码,我将对其进行分析。
您可以为jQuery编写一个简单的扩展方法:
jQuery.extend({
postJSON: function (url, data, callback) {
return jQuery.post(url, data, callback, "json");
}
});
然后在javascript块中执行以下操作:
$.postJSON('/controller/action',
{
Param1: 1,
Param2: 2
},
function(data){
alert(data.result);
});
在控制器中
[HttpPost]
public ActionResult Action(int Param1, int Param2)
{
return Json(new {
result : "It Worked"
});
}
下面是一个示例,它根据您的操作方法的响应来更改除法中的文本。。。
//a class with properties.
Class Priveleges{
Public string StatusMessage{get;set;}
Public int StatusCode{get;set;}
}
//code inside controller
[HttpGet]
Public JsonResult Index{
Priveleges obj=DecidePriveleges():
Return Json(obj,allowget.true);
}
Private Priveleges DecidePriveleges(){
Prilveleges obj;
//prepare object based on server response
If(response=="high"){
obj=new Priveleges(){
StatusMessage="high priveleges",
StatusCode=1}
}else if(response=="medium){
obj=new Priveleges(){
StatusMessage="medium priveleges",
StatusCode=2}
}else if(response=="low"){
Obj=new Priveleges(){
StatusMessage="low priveleges"‚
StatusCode=3}
}
Return obj;
//code inside ur view
//suppose you want to change the text inside
//ur div when the page loads..
<div id="statusDiv"></div>
//here is ur javascript.
$(document).ready(function(){
$.getJSON('/controller/Index',function(data){
$('#statusDiv').text(
'You have '+data.StatusMessage);
});
});
//here data,the parameter of getJson method.
//holds the data coming from our action
//method...
很抱歉代码格式。。从我的手机上发布了代码。。。
希望这个小测验能有所帮助。。