问题
I am trying to grab just a single value from some json and am using Chrome's javascript console to try and debug it. I have tried Request["id"], and Request.Params["id"] and it doesn't grab anything. I have verified via the chrome javascript debugger that the value is going across but I can't pull the value out using webmatrix. Can anybody please help?
code from Default.cshtml
$.ajax({
type: 'POST',
data: encodedItemId, //looks like { id : value }
dataType: 'json',
url: '/actions/act_markCompleted.cshtml',
success: function(data){
alert(data); //trying to view the json data
}
});
Posts via ajax to this page, act_markCompleted.cshtml
@{
var itemId = Request["id"];
var data = "The id is: " + itemId;
var db = Database.Open("VacationBuddyDB");
var sql = "UPDATE Items SET completed = @0 WHERE Id = @1";
db.Execute(sql, true, itemId.AsInt());
Json.Write(data, Response.Output);
}
回答1:
The following should work:
$.ajax({
type: 'POST',
data: { id : 'value' },
dataType: 'json',
url: '/actions/act_markCompleted.cshtml',
success: function(data) {
alert(data);
}
});
Make sure that you are not sending { id : 'value' }
as a string but rather as a javascript object as shown. Also if you are running this ajax request inside the callback of the click action of some link or form submit make sure that you cancel the default action by returning false at the end or the ajax request might not have time to execute.
来源:https://stackoverflow.com/questions/6637818/how-do-i-get-a-single-json-value-using-webmatrix-razor