Thứ Sáu, 18 tháng 8, 2017

Cách sử dụng AjaxJquery

$.ajax({
  type: 'GET',
  url: filename,
  data: data,
  async: false,
  beforeSend: function (xhr) {
    if (xhr && xhr.overrideMimeType) {
      xhr.overrideMimeType('application/json;charset=utf-8');
    }
  },
  dataType: 'json',
  success: function (data) {
    //Do stuff with the JSON data
  }
});
[HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult SendContact(Contact item)
        {
            if (ModelState.IsValid)
            {
                _context.Contacts.Add(item);
                _context.SaveChanges();
                return Json(new { success = true}, JsonRequestBehavior.AllowGet);
            }


            return Json(new { success = false }, JsonRequestBehavior.AllowGet);
        }
var dataString = $('#contact-form').serialize(); // Collect data from form
            $.ajax({
                type: "POST",
                url: $('#contact-form').attr('action'),
                data: dataString,
                dataType: 'json',
                timeout: 6000,
                error: function (request, error) {

                },
                success: function (response) {

                    //response = $.parseJSON(response);
                    //alert(response);
                    if (response.success) {
                        $('#successSend').show();
                        $("#name").val('');
                        $("#email").val('');
                        $("#comment").val('');
                    } else {
                        $('#errorSend').show();
                    }
                }
            });
            return false;


Nguồn: https://www.sitepoint.com/ajaxjquery-getjson-simple-example/

Không có nhận xét nào:

Đăng nhận xét

Subscribe

Flickr