原生 JS Ajax,GET和POST 请求实例代码_javascript技巧_脚本之家 https://www.jb51.net/article/86157.htm

更新时间:2016年06月08日 10:18:06

javascript/js的ajax的GET请求代码如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<script type="text/javascript">
/* 创建 XMLHttpRequest 对象 */
var xmlHttp;
function GetXmlHttpObject(){
  if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }else{// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  return xmlhttp;
}
// -----------ajax方法-----------//
function getLabelsGet(){
  xmlHttp=GetXmlHttpObject();
  if (xmlHttp==null){
    alert('您的浏览器不支持AJAX!');
    return;
  }
  var id = document.getElementById('id').value;
  var url="http://www.Leefrom.com?id="+id+"&t/"+Math.random();
  xmlHttp.open("GET",url,true);
  xmlHttp.onreadystatechange=favorOK;//发送事件后,收到信息了调用函数
  xmlHttp.send();
}
function getOkGet(){
  if(xmlHttp.readyState==1||xmlHttp.readyState==2||xmlHttp.readyState==3){
    // 本地提示:加载中
  }
  if (xmlHttp.readyState==4 && xmlHttp.status==200){
    var d= xmlHttp.responseText;
    // 处理返回结果
  }
}
</script>

javascript/js的ajax的POST请求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<script type="text/javascript">
/* 创建 XMLHttpRequest 对象 */
var xmlHttp;
function GetXmlHttpObject(){
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
// -----------ajax方法-----------//
function getLabelsPost(){
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null){
alert('您的浏览器不支持AJAX!');
return;
}
var url="http://www.lifefrom.com/t/"+Math.random();
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
xmlHttp.onreadystatechange=getLabelsOK;//发送事件后,收到信息了调用函数
}
function getOkPost(){
if(xmlHttp.readyState==1||xmlHttp.readyState==2||xmlHttp.readyState==3){
// 本地提示:加载中/处理中
}
if (xmlHttp.readyState==4 && xmlHttp.status==200){
var d=xmlHttp.responseText; // 返回值
// 处理返回值
}
}
</script>

注意:XMLHttpRequest 是 AJAX 的基础,在创建 XMLHttpRequest 对象时,必须与你写的ajax方法在同一个‘<script></script>'标签中!否则ajax请求会出错,并无法返回数据。 javascript/js的ajax的POST/GET请求。

  • 使用 fetch 代替 ajax(在不支持的浏览器上使用 XHR);

Using Fetch - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used by other technologies such as Service Workers. Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP.

The fetch specification differs from jQuery.ajax() in two main ways:

  • The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
  • By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).
    Since Aug 25, 2017. The spec changed the default credentials policy to same-origin. Firefox changed since 61.0b13.

A basic fetch request is really simple to set up. Have a look at the following code:

fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});

Here we are fetching a JSON file across the network and print it to the console. The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object).

This is just an HTTP response of course, not the actual JSON. To extract the JSON body content from the response, we use the json() method (defined on the Body mixin, which is implemented by both the Request and Response objects.)

Note: The Body mixin also has similar methods to extract other types of body content; see the Body section for more.

Fetch requests are controlled by the connect-src directive of Content Security Policy rather than the directive of the resources it's retrieving.

Supplying request optionsSection

The fetch() method can optionally accept a second parameter, an init object that allows you to control a number of different settings:

See fetch() for the full options available, and more details.

// Example POST method implementation:

postData(`http://example.com/answer`, {answer: 42})
.then(data => console.log(JSON.stringify(data))) // JSON-string from `response.json()` call
.catch(error => console.error(error)); function postData(url = ``, data = {}) {
// Default options are marked with *
return fetch(url, {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
credentials: "same-origin", // include, *same-origin, omit
headers: {
"Content-Type": "application/json; charset=utf-8",
// "Content-Type": "application/x-www-form-urlencoded",
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data), // body data type must match "Content-Type" header
})
.then(response => response.json()); // parses response to JSON
}

Sending a request with credentials includedSection

To cause browsers to send a request with credentials included, even for a cross-origin call, add credentials: 'include' to the init object you pass to the fetch() method.

fetch('https://example.com', {
credentials: 'include'
})

If you only want to send credentials if the request URL is on the same origin as the calling script, add credentials: 'same-origin'.

// The calling script is on the origin 'https://example.com'

fetch('https://example.com', {
credentials: 'same-origin'
})

To instead ensure browsers don’t include credentials in the request, use credentials: 'omit'.

fetch('https://example.com', {
credentials: 'omit'
})

Uploading JSON dataSection

Use fetch() to POST JSON-encoded data.

var url = 'https://example.com/profile';
var data = {username: 'example'}; fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(data), // data can be `string` or {object}!
headers:{
'Content-Type': 'application/json'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

Uploading a fileSection

Files can be uploaded using an HTML <input type="file" /> input element, FormData()and fetch().

var formData = new FormData();
var fileField = document.querySelector("input[type='file']"); formData.append('username', 'abc123');
formData.append('avatar', fileField.files[0]); fetch('https://example.com/profile/avatar', {
method: 'PUT',
body: formData
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', JSON.stringify(response)));

Uploading multiple filesSection

Files can be uploaded using an HTML <input type="file" /> input element, FormData()and fetch().

var formData = new FormData();
var photos = document.querySelector("input[type='file'][multiple]"); formData.append('title', 'My Vegas Vacation');
formData.append('photos', photos.files); fetch('https://example.com/posts', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

Checking that the fetch was successfulSection

fetch() promise will reject with a TypeError when a network error is encountered or CORS is misconfigured on the server side, although this usually means permission issues or similar — a 404 does not constitute a network error, for example. An accurate check for a successful fetch() would include checking that the promise resolved, then checking that the Response.ok property has a value of true. The code would look something like this:

fetch('flowers.jpg').then(function(response) {
if(response.ok) {
return response.blob();
}
throw new Error('Network response was not ok.');
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
}).catch(function(error) {
console.log('There has been a problem with your fetch operation: ', error.message);
});

Supplying your own request objectSection

Instead of passing a path to the resource you want to request into the fetch() call, you can create a request object using the Request() constructor, and pass that in as a fetch()method argument:

var myHeaders = new Headers();

var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' }; var myRequest = new Request('flowers.jpg', myInit); fetch(myRequest).then(function(response) {
return response.blob();
}).then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});

Request() accepts exactly the same parameters as the fetch() method. You can even pass in an existing request object to create a copy of it:

var anotherRequest = new Request(myRequest, myInit);

This is pretty useful, as request and response bodies are one use only. Making a copy like this allows you to make use of the request/response again, while varying the init options if desired. The copy must be made before the body is read, and reading the body in the copy will also mark it as read in the original request.

Note: There is also a clone() method that creates a copy. Both methods of creating a copy will fail if the body of the original request or response has already been read, but reading the body of a cloned response or request will not cause it to be marked as read in the original.

HeadersSection

The Headers interface allows you to create your own headers object via the Headers()constructor. A headers object is a simple multi-map of names to values:

var content = "Hello World";
var myHeaders = new Headers();
myHeaders.append("Content-Type", "text/plain");
myHeaders.append("Content-Length", content.length.toString());
myHeaders.append("X-Custom-Header", "ProcessThisImmediately");

The same can be achieved by passing an array of arrays or an object literal to the constructor:

myHeaders = new Headers({
"Content-Type": "text/plain",
"Content-Length": content.length.toString(),
"X-Custom-Header": "ProcessThisImmediately",
});

The contents can be queried and retrieved:

console.log(myHeaders.has("Content-Type")); // true
console.log(myHeaders.has("Set-Cookie")); // false
myHeaders.set("Content-Type", "text/html");
myHeaders.append("X-Custom-Header", "AnotherValue"); console.log(myHeaders.get("Content-Length")); // 11
console.log(myHeaders.get("X-Custom-Header")); // ["ProcessThisImmediately", "AnotherValue"] myHeaders.delete("X-Custom-Header");
console.log(myHeaders.get("X-Custom-Header")); // [ ]

Some of these operations are only useful in ServiceWorkers, but they provide a much nicer API for manipulating headers.

All of the Headers methods throw a TypeError if a header name is used that is not a valid HTTP Header name. The mutation operations will throw a TypeError if there is an immutable guard (see below). Otherwise they fail silently. For example:

var myResponse = Response.error();
try {
myResponse.headers.set("Origin", "http://mybank.com");
} catch(e) {
console.log("Cannot pretend to be a bank!");
}

A good use case for headers is checking whether the content type is correct before you process it further. For example:

fetch(myRequest).then(function(response) {
var contentType = response.headers.get("content-type");
if(contentType && contentType.includes("application/json")) {
return response.json();
}
throw new TypeError("Oops, we haven't got JSON!");
})
.then(function(json) { /* process your JSON further */ })
.catch(function(error) { console.log(error); });

GuardSection

Since headers can be sent in requests and received in responses, and have various limitations about what information can and should be mutable, headers objects have a guard property. This is not exposed to the Web, but it affects which mutation operations are allowed on the headers object.

Possible guard values are:

  • none: default.
  • request: guard for a headers object obtained from a request (Request.headers).
  • request-no-cors: guard for a headers object obtained from a request created with Request.mode no-cors.
  • response: guard for a Headers obtained from a response (Response.headers).
  • immutable: Mostly used for ServiceWorkers; renders a headers object read-only.

Note: You may not append or set a request guarded Headers’ Content-Length header. Similarly, inserting Set-Cookie into a response header is not allowed: ServiceWorkers are not allowed to set cookies via synthesized responses.

Response objectsSection

As you have seen above, Response instances are returned when fetch() promises are resolved.

The most common response properties you'll use are:

  • Response.status — An integer (default value 200) containing the response status code.
  • Response.statusText — A string (default value "OK"), which corresponds to the HTTP status code message.
  • Response.ok — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a Boolean.

They can also be created programmatically via JavaScript, but this is only really useful in ServiceWorkers, when you are providing a custom response to a received request using a respondWith() method:

var myBody = new Blob();

addEventListener('fetch', function(event) { // ServiceWorker intercepting a fetch
event.respondWith(
new Response(myBody, {
headers: { "Content-Type" : "text/plain" }
})
);
});

The Response() constructor takes two optional arguments — a body for the response, and an init object (similar to the one that Request() accepts.)

Note: The static method error() simply returns an error response. Similarly, redirect() returns a response resulting in a redirect to a specified URL. These are also only relevant to Service Workers.

BodySection

Both requests and responses may contain body data. A body is an instance of any of the following types:

The Body mixin defines the following methods to extract a body (implemented by both Request and Response). These all return a promise that is eventually resolved with the actual content.

This makes usage of non-textual data much easier than it was with XHR.

Request bodies can be set by passing body parameters:

var form = new FormData(document.getElementById('login-form'));
fetch("/login", {
method: "POST",
body: form
});

Both request and response (and by extension the fetch() function), will try to intelligently determine the content type. A request will also automatically set a Content-Type header if none is set in the dictionary.

Feature detectionSection

Fetch API support can be detected by checking for the existence of HeadersRequestResponse or fetch() on the Window or Worker scope. For example:

if (self.fetch) {
// run my fetch request here
} else {
// do something with XMLHttpRequest?
}

PolyfillSection

To use Fetch in unsupported browsers, there is a Fetch Polyfill available that recreates the functionality for non-supporting browsers.

使用 fetch 代替 ajax(在不支持的浏览器上使用 XHR); This kind of functionality was previously achieved using XMLHttpRequest.的更多相关文章

  1. Fetch和ajax的比较和区别

    传统 Ajax 已死,Fetch 永生   Ajax 不会死,传统 Ajax 指的是 XMLHttpRequest(XHR),未来现在已被 Fetch 替代. 最近把阿里一个千万级 PV 的数据产品全 ...

  2. 使用 Fetch完成AJAX请求

    使用 Fetch完成AJAX请求 写在前面 无论用JavaScript发送或获取信息,我们都会用到Ajax.Ajax不需要刷新页面就能发送和获取信息,能使网页实现异步更新. 几年前,初始化Ajax一般 ...

  3. 三种获取数据的方法fetch和ajax和axios

    一 .fetch用法 ( 本人比较喜欢fetch,代码精简,虽说目前axios比较流行,但是fetch很多大厂已经开始用fetch开始封装了, 我觉得以后fetch会取代axios和ajax ) 1. ...

  4. 使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器

    使用ajax上传图片,支持图片即时浏览,支持js图片压缩后上传给服务器 ajax上传主要使用了 var reader = new FileReader() 此方法 js图片压缩主要是利用canvas进 ...

  5. 基于bootstrap的上传插件fileinput实现ajax异步上传功能(支持多文件上传预览拖拽)

    首先需要导入一些js和css文件 ? 1 2 3 4 5 6 <link href="__PUBLIC__/CSS/bootstrap.css" rel="exte ...

  6. skymvc文件上传支持多文件上传

    skymvc文件上传支持多文件上传 支持单文件.多文件上传 可以设定 文件大小.存储目录.文件类型 //上传的文件目录 $this->upload->uploaddir="att ...

  7. 利用 html的锚点(元素a)功能实现ajax单页面应用的浏览器后退前进功能

    一.问题 随着AJax技术的普及,单页面web程序的应用越来越广泛. 所谓单页面应用程序,简单的说,就是应用只有一个主网页,第一次加载后,后续页面只会利用js和ajax到服务器获取数据进行页面的局部刷 ...

  8. Jquery图片上传组件,支持多文件上传

    Jquery图片上传组件,支持多文件上传http://www.jq22.com/jquery-info230jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传.取消. ...

  9. ajaxfileupload多文件上传 - 修复只支持单个文件上传的bug

    搜索: jquery ajaxFileUpload AjaxFileUpload同时上传多个文件 原生的AjaxFileUpload插件是不支持多文件上传的,通过修改AjaxFileUpload少量代 ...

随机推荐

  1. n&(n-1)的用途

    最近做LeetCode上面的题目,发现很多题目都用到了n&(n-1).感觉真是神通广大,下面就目前所看到的一些用途总结一下: 1,求一个int类型数是否为2的幂 当n=4时,二进制为:0100 ...

  2. POJ 2643 Election

    Election Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 3558   Accepted: 1692 Descript ...

  3. nginx报错 too many open files in system

    系统进不去了,用ssh连接服务器也非常慢,负载均衡显示后端连接异常,重启mysql数据库,发现经常重启,或者直接关机,访问页面也访问不到. http://www.51testing.com/html/ ...

  4. spring mvc 单元测试示例

    import java.awt.print.Printable; import java.io.IOException; import javax.servlet.http.HttpServletRe ...

  5. Spring学习之路——简单入门HelloWorld

    Spring简单介绍 Spring是一个提供了解决J2EE问题的一站式框架. Spring的核心是反转控制,通过配置文件完成业务对象之间的依赖注入,他鼓励一个良好的习惯,就是注入对接口编程而不是对类编 ...

  6. HTML 文档之 Head 最佳实践--摘抄

    HTML 文档之 Head 最佳实践 story 01-10 阅读 353 收藏 0 收藏 这篇文章整理了作者认可的一些最佳实践,写在这里与各位分享 阅读原文折叠收起 HTML 文档之 Head 最佳 ...

  7. EMD距离

    一.场景介绍   最近在研究一个场景:图片质量评分,给一张图片一个预测的分数.   里面提到了用 EMD(Earth Mover’s Distance)算法来评估两张图片之间的分布距离.下面主要讲解下 ...

  8. 自定义Navigation按钮及Title

    导航栏自带的按钮,时常不能满足要求,所以深深需要进行各种定制. 写一个UINavigationItem的category // UINavigationItem+CB_ChangeButton.h 
 ...

  9. shell高级-----初识sed和gawk

    sed编辑器 sed说明 sed是Linux下一款功能强大的非交互流式文本编辑器,可以对文本文件进行增.删.改.查等操作,支持按行.按字段.按正则匹配文本内容,灵活方便,特别适合于大文件的编辑. 替换 ...

  10. [Code Plus#4] 最短路

    题目背景 在北纬 91° ,有一个神奇的国度,叫做企鹅国.这里的企鹅也有自己发达的文明,称为企鹅文明.因为企鹅只有黑白两种颜色,所以他们的数学也是以二进制为基础发展的. 比如早在 1110100111 ...