How can I call Ajax from Javascript?
I have a drop down list
<select onchange="alert(this.value);">
<option selected="selected" value="cat">cat</option>
<option value="dog">dog</option>
</select>
I would like to make it so that when the users changes a value then an AJAX call is s开发者_运维百科ent to my MVC controller which then updates the database.
I've done this with forms but never from javascript. Does anyone have an example of how this could be done.
thanks,
If you are using jQuery:
<select id="category" name="category">
<option selected="selected" value="cat">cat</option>
<option value="dog">dog</option>
</select>
and then:
$(function() {
$('#category').change(function() {
$.post('/home/save', { selectedCategory: $(this).val() }, function(result) {
alert('success');
});
});
});
which will send an AJAX request to the following action:
[HttpPost]
public ActionResult Save(string selectedCategory)
{
// TODO: process the selected category
return Json(new { success = true });
}
精彩评论