GVKun编程网logo

AJAX简单实例(GET、POST)(ajax简单实例)

12

对于AJAX简单实例感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍GET、POST,并为您提供关于ajax传值ajax、post、get、ajax引擎对象的属性方法事件、及其get、post传

对于AJAX简单实例感兴趣的读者,本文将会是一篇不错的选择,我们将详细介绍GET、POST,并为您提供关于ajax 传值 ajax、post、get、ajax 引擎对象的属性方法事件、及其 get、post 传参、ajax 请求基于 restFul 的 WebApi (post、get、delete、put)、ajax--表单get、post方法向后台传输数据的有用信息。

本文目录一览:

AJAX简单实例(GET、POST)(ajax简单实例)

AJAX简单实例(GET、POST)(ajax简单实例)

1、GET方式

首先是test.jsp

<script type="text/javascript">
function gethttprequest(){
  	var xmlhttp;
  	try{
  		xmlhttp=new XMLHttpRequest();
  	}catch(e){
  		try{
  			xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
  		}catch(e)
  		{
  			try{
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
			}catch(e){}
  		}
  	}
  	return xmlhttp;
}

window.onload=function(){
var xmlhttp;
	document.getElementById("ok").onclick=function(){
	//获取XMLHttpRequest对象
  		
  		xmlhttp=gethttprequest();
  		
  		//与服务器建立连接
  		xmlhttp.open("get","./servlet/Aservlet?timestamp="+new Date().getTime()+"&a=998",true);
  		
  		//发送数据
  		xmlhttp.send("b=666&c=777");
  		//响应服务器
  		
  		xmlhttp.onreadystatechange=function(){
  			alert(xmlhttp.readyState);
  			if(xmlhttp.readyState==4){
  				if(xmlhttp.status==200){
  					var data=xmlhttp.responseText;
  					alert(data);
  				}
  			}
  		}
	}
}
		
</script>
  </head>
  
  <body>
    <form action="" enctype="application/x-www-form-urlencoded">
    	<input type="button" name="ok" id="ok" value="测试"/>
    </form>
  </body>

其次是Aservlet.java
public void doGet(HttpServletRequest request,HttpServletResponse response)
			throws servletexception,IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		PrintWriter out=response.getWriter();
		
		System.out.println("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
		System.out.println("请求的方式:"+request.getmethod());
		//从test.jsp中的url中接受参数a的值
		System.out.println("参数a的值:"+request.getParameter("a"));
		//从test.jsp中的send中接受参数b,c的值,结果是不能接受到的,因为是GET方式
		System.out.println("参数b的值"+request.getParameter("b"));
		System.out.println("参数b的值"+request.getParameter("c"));
		//给test.jsp页面传送值
		out.println("dddddddddd");
	}

最后是web.xml
<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Aservlet</servlet-name>
    <servlet-class>one.Aservlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Aservlet</servlet-name>
    <url-pattern>/servlet/Aservlet</url-pattern>
  </servlet-mapping>

2、POST方式

基本和GET方式一样,只要作如下修改:

xmlhttp.open("post",true);

在调用open函数之后

xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

说明:

使用POST方式,send()可以发送消息,Aservelt.java可以接受到,而GET方式则收不到,即send(null)就可以了。

ajax 传值 ajax、post、get

ajax 传值 ajax、post、get

$.ajax()这个是jQuery 的底层 AJAX 实现。简单易用的高层实现见 $.get,$.post 等。
这里有几个Ajax事件参数:beforeSend ,success ,complete ,error 。
$.ajax({
url: 'consignAction.jsp',
type: 'POST',
da ta:{'ids':ids,'act ion':'del'},
dataType: 'text',
async: false,//同步
timeout: 5000,
error: function(){
alert('操作错误,请与系统管理员联系!');
},
success: function(da ta){
if($.trim(da ta) != 'true'){
alert(&quot;解除委托成功&quot;);
}
}
});


$.post('.url?action=getTransferInTicketDetail',
{ from_no: rowData.FROM_NO,to_no: rowData.TO_NO },function (data) {


},'json');


$.get('url?action=getTransferInTicketDetail',function (data) {

},'json');

ajax 引擎对象的属性方法事件、及其 get、post 传参

ajax 引擎对象的属性方法事件、及其 get、post 传参

XMLHttpRequest 对象(即 Ajax 对象)的属性,方法,事件
事件
onreadystatechange: “请求状态” 改变监听器,每当 readyState 属性的值发生变化时,该监听器上绑定
的函数将会执行

属性
readyState: “请求状态”,通过 0,1,2,3,4 这 5 个数字表示这次请求的状态,当该值变为 4 时,表示响应完成
          status:“http 状态码”             200            404                          500
          statusText:“http 状态描述” OK        Not Found        Internal Server Error
          responseText: 服务器返回普遍文本信息
          responseXML:服务器返回的 XML 数据(仅作了解)

方法
open (method,url,async): 表示创建一个 Http 请求;
      参数:
               method: 表示请求方式(get/post)
               url: 表示请求的路径
               async: 表示是否异步请求(true/false)


send (param):发送 http 请求
          参数:
                  param: 表示 post 请求发送的请求数据


setRequestHeader (key,value): 设置请求头,必须在 open 方法和 send 方法之间
         如果我们希望通过 post 方式发送数据,需添加这样一个请求头:
         xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
        参数
               key:请求头的键
               value:请求头的值

get 方式传参
xhr.open("get","getdata?name=zhangsan&age=18",true);
xhr.send();

post 方式传参
xhr.open("post","getdata",true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
xhr.send("name=lisi&age=18");

ajax 请求基于 restFul 的 WebApi (post、get、delete、put)

ajax 请求基于 restFul 的 WebApi (post、get、delete、put)

近日逛招聘软件,看到部分企业都要会编写、请求 restFul 的 webapi。正巧这段时间较为清闲,于是乎打开 vs 准备开撸。

 

1. 何为 restFul?

restFul 是符合 rest 架构风格的网络 API 接口。

rest 是一种软件架构的编码风格,是根据网络应用而去设计和开发的一种可以降低开发复杂度的编码方式,并且可以提高程序的可伸缩性 (增减问题)。

几种较为常见的操作类型:get (查询)、post (新增)、put (修改)、delete (删除)

 

2.restFul 标准的 WebApi 搭建以及部署在 iis 上

在这里为了方便,使用的 ef 框架,在创建读 / 写控制器时直接引用了模型类

 

 

控制器直接帮我帮 crud 的方法都写好了,按照注释的请求规则,可直接使用。代码如下:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using webapi;

namespace webapi.Controllers
{
    public class ProductsController : ApiController
    {
        private DtoolsEntities db = new DtoolsEntities();

        // GET: api/Products
        [HttpGet]
        public IQueryable<Product> GetProduct()
        {
            return db.Product.OrderByDescending(p => p.AddDate).Take(10);
        }

        // GET: api/Products/5
        [HttpGet]
        [ResponseType(typeof(Product))]
        public IHttpActionResult GetProduct(int id)
        {
            Product product = db.Product.Find(id);
            if (product == null)
            {
                return NotFound();
            }

            return Ok(product);
        }

        // PUT: api/Products/5  update 
        [HttpPut]
        [ResponseType(typeof(void))]
        public IHttpActionResult PutProduct(int id, Product product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != product.Id)
            {
                return BadRequest();
            }
            product.AddDate = DateTime.Now;
            db.Entry(product).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }


        // POST: api/Products  
        [HttpPost]
        [ResponseType(typeof(Product))]
        public IHttpActionResult PostProduct(Product product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }
            product.AddDate = DateTime.Now;
            db.Product.Add(product);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = product.Id }, product);
        }

        // DELETE: api/Products/5  
        [HttpDelete]
        [ResponseType(typeof(Product))]
        public IHttpActionResult DeleteProduct(int id)
        {
            Product product = db.Product.Find(id);
            if (product == null)
            {
                return NotFound();
            }

            db.Product.Remove(product);
            db.SaveChanges();

            return Ok(product);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool ProductExists(int id)
        {
            return db.Product.Count(e => e.Id == id) > 0;
        }
    }
}

 

每个控制器前根据类型最好指定 [HttpGet]  [HttpPost]   [HttpPut]  [HttpDelete],因为服务器是根据请求类型自动映射匹配控制器名称,加上特性,避免出错。

weiapi 设置中指定 json 格式,避免数据类型异常

webapi 的搭建基本没有问题了。接下来就是部署在 iis 上,这里不多做描述,不懂如何部署 iis 可点击这里 (会被揍吗?)

 

3. 前台 ajax 请求页面的编写

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript">

        //部署在iis上的webapi接口具体请求路径
        var httpUrl = "http://192.168.0.142:8018/api/Products";

        $(function () {
            $.ajax({
                url: httpUrl,
                type: "GET",
                dataType: "json",
                success: function (data) {
                    $.each(data, function (index, item) {
                        var tr = $("<tr/>");
                        $("<td/>").html(item["ProductName"]).appendTo(tr);
                        $("<td/>").html(item["Brand"]).appendTo(tr);
                        $("<td/>").html(item["ASIN"]).appendTo(tr);
                        $("<td/>").html(item["SKU"]).appendTo(tr);
                        $("<button id =''d'' onclick=''del(" + item["Id"] + ")''>").html("删除").appendTo(tr);
                        $("<button id =''u'' onclick=''update(" + item["Id"] + ")''>").html("更新").appendTo(tr);
                        tr.appendTo("#tab");
                    });
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest + "," + textStatus + "," + errorThrown);
                }
            });

        });

        //修改
        function update(id) {
            $.ajax({
                url: httpUrl + "?id=" + id,
                type: "Put",
                data: { "id": id, "ProductName": ''男士领带'', "Brand": ''海澜之家'', "ASIN": ''SAD498AE1'', "SKU": ''98DA7E9QE-SDAE'', "StoreName": ''海澜之家京东自营店'' },
                dataType: "json",
                success: function (data) {
                    location.reload();
                }
            })
        }

        //新增
        function add() {
            $.ajax({
                url: httpUrl,
                type: "Post",
                data: { "ProductGuid": newGuid(), "ProductName": ''男士衬衫'', "Brand": ''海澜之家'', "ASIN": ''SAD498AE1'', "SKU": ''98DA7E9QE-SDAE'', "StoreName": ''海澜之家天猫旗舰店'' },
                dataType: "json",
                success: function (data) {
                    location.reload();
                }
            })
        }

        //删除
        function del(id) {
            $.ajax({
                url: httpUrl+"/" + id,
                type: "Delete",
                dataType: "json",
                success: function (data) {
                    location.reload();
                }
            });
        }

        //生成guid
        function newGuid() {
            var guid = "";
            for (var i = 1; i <= 32; i++) {
                var n = Math.floor(Math.random() * 16.0).toString(16);
                guid += n;
                if ((i == 8) || (i == 12) || (i == 16) || (i == 20))
                    guid += "-";
            }
            return guid;
        }
    </script>
</head>
<body>
    <div>
        <table id="tab">
            <tr>
                <th>产品名称</th>
                <th>产品品牌</th>
                <th>ASIN</th>
                <th>SKU</th>
            </tr>
        </table>
        <button id="add" onclick="add()">add</button>
    </div>

</body>
</html>

 

前端,后端代码都写完了。只剩测试了。想都不用想肯定会出问题的,因为涉及到了跨域请求等,接下来就为大家解决问题。

问题一:ajax 请求,涉及到 cors 跨域,请求失败

  问题介绍及原因分析:

           CORS 是一个 W3C 标准,全称是” 跨域资源共享”。它允许浏览器向跨源服务器,发出 XMLHttpRequest 请求,基本上目前所有的浏览器都实现了 CORS 标准,其实目前几乎所有的浏览器 ajax 请求都是基于 CORS 机制的。
         跨域问题一般发生在 Javascript 发起 AJAX 调用,因为浏览器对于这种请求,所给予的权限是较低的,通常只允许调用本域中的资源,除非目标服务器明确地告知它允许跨域调用。所以,跨域的问题虽然是由浏览器的行为产生出来的,但解决的方法却            是在服务端。因为不可能要求所有客户端降低安全性。

        解决方案:

                           web.config 修改配置文件,使服务端支持跨域请求

 

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <!--服务器端返回Response header  后接URL或*  表示允许-->
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
     <!--支持请求的类型--> <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" /> </customHeaders> </httpProtocol> <handlers> <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> </handlers> </system.webServer>

 

 

问题二:get、post 可正常请求,put、delete 出现 405(Method Not Allowed)  注意:我提交 Put 的请求,浏览器响应的是 Request Method:PUT

  问题介绍及原因分析:

           有些人会问:我刚刚在服务端设置了允许 put delete 请求了,浏览器上服务端的响应也看到了支持 put delete,为啥服务端还是拒绝呢?

           一切都是 iis 的 WebDAV (Web Distribution Authorization Versioning) Publish 惹的祸,WebDAV 是基于 HTTP 协议的拓展,添加了很多 Method 用于管理服务器上的文件。若安装了 WebDAV, 那么 iis 所有的 site 都会默认使用 WebDAV Module 与 WebDAV Handler。

          WebDAV Handler 的默认配置是处理如下 Method:PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK。所以浏览器发送的 put delete 请求都会被拦截并交给 WebDAV Handler 来处理,并且 WebDAV Handler 会默认拒绝请求

        解决方案:

        既然我们找到了问题所在点,那么解决方案应然而生,那就是在配置文件里移除 ebDAVModule 和 WebDAVHandler 或者在系统中直接移除 WebDAV

<system.webServer>
    <!--以下配置为了让IIS 7+支持Put/Delete方法-->
    <httpProtocol>
      <customHeaders>
        <!--服务器端返回Response header  后接URL或*  表示允许-->
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <validation validateIntegratedModeConfiguration="false"/>
    <handlers>
      <!--移除WebDAV协议-->
      <remove name="WebDAV"/>
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <!--支持所有方式的请求-->
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
    <!--IIS7/7.5上必须加这个配置,否则访问报错-->
    <modules  runAllManagedModulesForAllRequests="true">
      <!--移除WebDAV协议-->
      <remove name="WebDAVModule"/>
      <remove name="TelemetryCorrelationHttpModule" />
      <add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
    </modules>
  </system.webServer>

 

问题三:put delete 请求,又出现了 405(Method Not Allowed)

  问题介绍及原因分析:

           大家发现没有,问题二 put 提交,Request Method 就是 put,Delete 提交,Request Method 就是 Delete。然而在这里统统都是 OPTIONS。那么这个 OPTIONS 到底是个啥呢?

           Preflighted Requests(预检请求)
           Preflighted Requests 是 CORS 中一种透明服务器验证机制。预检请求首先需要向另外一个域名的资源发送一个 HTTP OPTIONS 请求头,其目的就是为了判断实际发送的请求是否是安全的
          下面的 2 种情况需要进行预检:
          1、简单请求,比如使用 Content-Type 为 application/xml 或 text/xml 的 POST 请求;
          2、请求中设置自定义头,比如 X-JSON、X-MENGXIANHUI 等。

          原来 put、delete 请求如果头部设置了 XMLHttpRequest.setRequestHeader ("Content-Type", "application/json") 之前还发送了一次预检请求。

        解决方案:

          既然是多的一次请求,那我们就在服务端过滤掉就好了。

          Global.asac 添加以下方法就行了

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace webapi
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        protected void Application_BeginRequest()
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.End();
            }
        }
    }
}

 

到这里,ajax 跨域实现 RestFul 请求,已经是能正常运行了。剩下的只是安全校验、身份认证、异常记录等,就能放到生产环境了。这里就不多做描述了,毕竟博主还是上班族...

如有错误,欢迎大家指正~

 

 

原文出处:https://www.cnblogs.com/wangjifeng23/p/10071880.html

ajax--表单get、post方法向后台传输数据

ajax--表单get、post方法向后台传输数据

为了前端与后台进行交互,我们使用ajax来完成这些功能。

我们首先了解,什么是ajax?

Asynchronous JavaScript and XML

通过在后台与服务器进行少量数据交换,Ajax 可以使网页实现异步更新,可以局部刷新而不必整个页面整体刷新。

如何与服务器进行数据交换?

首先,需要自己搭建服务器,在服务端的环境中可运行PHP语言

从网页进入服务器有三种基本方式:

1.   localhost:+端口号
2.   127.0.0.1+端口号
3.   ip+端口号

然后,和服务器端的PHP页面建立联系

如下例子:在html页面中的form表单中,与 05.2.PHP 建立联系 ,数据传递方式为POST。

<form action="05.2.PHP" method="post">
    <input type="text" placeholder="请输入用户名" name="userName">
    <input type="submit" placeholder="登录">
</form>

下面是05.2.PHP页面的内容:

<?PHP
    echo "这个为post提交的页面";
    echo $_POST[‘userName‘];
    echo ‘<h1>‘.$_POST[‘userName‘].‘欢迎你</h1>‘;   
        //在PHP中字符串拼接使用的是.
?>    

输入 jj  结果如下:

分享图片

如果使用get方式传递数据,则在PHP页面中使用$_GET[‘‘]方法。

关于AJAX简单实例GET、POST的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于ajax 传值 ajax、post、get、ajax 引擎对象的属性方法事件、及其 get、post 传参、ajax 请求基于 restFul 的 WebApi (post、get、delete、put)、ajax--表单get、post方法向后台传输数据等相关内容,可以在本站寻找。

本文标签: