1 <!DOCTYPE html> 2 3 <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 4 <head> 5 <meta charset="utf-8" /> 6 <title></title> 7 8 </head> 9 <body> 10 <script> 11 //第一步创建请求对象; 12 //第二步监听请求状态 13 //第三部配置请求信息 14 //第四部发送 15 function createxmlHttpRequest() { 16 var xmlhttp; 17 if (window.XMLHttpRequest) { 18 //code for IE7+,Firefox,Chrome,Opera,Safari 19 xmlhttp = new XMLHttpRequest(); 20 } 21 else { 22 //code for IE6,IE5 23 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); 24 } 25 xmlhttp.onreadystatechange = function () { 26 //readyState存有XMLHttpRequest的状态。从0到4发生变化。0:请求未初始化1:服务器连接已建成2:请求已接收3:请求处理:4:请求已完成,且已就绪 27 //200:ok 404:未找到页面 28 if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { 29 document.getElementById("id").innerHTML = xmlhttp.responseText;//responseText获得字符串形式的响应数据并替换文档指定内容(也可获取XML形式响应数据) 30 } 31 } 32 xmlhttp.open("请求方式Get/Post", "处理文件url", true)//bool值指定是否为异步传输 33 xmlhttp.send(); 34 } 35 </script> 36 <div id="id"></div> 37 <input type="button" value="DreamerAjax" /> 38 </body> 39 </html>
1 <!DOCTYPE html> 2 3 <html> 4 <head> 5 <meta name="viewport" content="width=device-width" /> 6 <title>View</title> 7 @*首先引入Jquery包*@ 8 <script src="~/Scripts/jquery-1.10.2.js"></script> 9 </head> 10 <body> 11 <script> 12 $(document).ready(function () { 13 var str = $("#Dreamerid").html; 14 //有Get,Post两种请求方式 15 $.get("处理文件url", { "key": "value","str":str }, function (response) { 16 //回调函数用于请求完成后对数据的处理 17 }) 18 }) 19 </script> 20 <div id="Dreamerid"> 21 DreamerJqueryAjax 22 </div> 23 </body> 24 </html>
1 <!DOCTYPE html> 2 3 <html> 4 <head> 5 <meta name="viewport" content="width=device-width" /> 6 <title>Index</title> 7 @*首先引入这俩个js文件*@ 8 <script src="~/Scripts/jquery-1.10.2.js"></script> 9 <script src="~/Scripts/jquery.validate.unobtrusive.js"></script> 10 <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script> 11 </head> 12 <body> 13 @using (Ajax.BeginForm("actionName", "routeVlaue", new AjaxOptions { 14 Confirm="是否提交?",//弹框提示确认提交 15 InsertionMode=InsertionMode.Replace,//将响应插入目标方式 16 UpdateTargetId = "id",//获取和设置更新元素 17 HttpMethod = "Post",//指定请求方式 18 OnSuccess = ""//获取请求后调用的函数 19 //.............. 20 })) 21 { 22 <div>括号内即为表单内容</div> 23 <input type="submit" value="获取请求" /> 24 } 25 </body> 26 </html>
MVC在使用Razor视图的情况下异步提交数据需要引入两个js文件一、jquery-1.10.2.js二、jquery.unobtrusive-ajax.js
MVC四中,在创建项目时已经引入这两个文件,MVC5中没有jquery.unobtrusive-ajax.js,解决办法:
点击工具选择NuGet包管理器展开,选择程序包管理控制台
在控制台PM>处分别粘贴一下内容Install-Package jQuery –version 1.10.2
Install-Package Microsoft.jQuery.Unobtrusive.Ajax –version 3.0.0
回车
原文:http://www.cnblogs.com/tutu926/p/Ajax.html