Linking

Capturing Life & Tech

  • 主页
  • 随笔
  • 关于我
所有文章 外链

Linking

Capturing Life & Tech

  • 主页
  • 随笔
  • 关于我

Ajax系列三-探讨XHR及POST数据

阅读数:次 2016-02-28
字数统计: 1.4k字   |   阅读时长≈ 6分

#Ajax系列三-深度探讨XHR及POST数据
Ajax异步原理

相当于在用户和服务器之间加了—个中间层(AJAX引擎),使用户操作与服务器响应异步化。并不是所有的用户请求都提交给服务器,像—些数据验证和数据处理等都交给Ajax引擎自己来做, 只有确定需要从服务器读取新数据时再由Ajax引擎代为向服务器提交请求。

ajax状态码

排序 时间 状态码
0 XHR对象刚创建 0
1 open建立连接成功 1
2 接收头信息完毕 2
3 接收body信息完毕 3
4 成功,结束后 4

ajax的好处就是不阻塞后面代码的执行。

status状态码为200,statusText状态文字是OK时,正确返回。

1
2
3
4
5
6
if(this.readyState == 4 && this.status == 200){
var str = '';
str = '状态码是 ' + this.status;
str += '状态文字是 ' + this.statusText;
document.getElementById('progress').innerHTML = str;
}

abort属性 –> 中断xhr

1
2
3
function stopxhr(){
xhr.abort();
}

send参数写法:k1=v1&k2=v2&k3=v3...

POST请求必须加上Content-Type: application/x-www-form-urlencoded

1
2
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send('username='+un+'&email='+eml);

Ajax返回值之XML类型

返回值类型:

不考虑HTML5最新标准,返回值有普通文本/xml文档两种类型

1
2
3
4
5
6
<?php 
header('Content-Type: text/xml');
?>
//此处空了一行
<?xml version="1.0" encoding="utf-8"?>
<bookstore><book bid='b0001'><title>天龙八部</title><intro>人生太苦了</intro></book></bookstore>

打开以上xxx.php,xml格式错误提示:

1
2
3
This page contains the following errors:
error on line 2 at column 6: XML declaration allowed only at the start of the document.
Below is a rendering of the page up to the first error.

错误显示:xml必须在文档的首行,如下

1
2
3
4
5
<?php 
header('Content-Type: text/xml');
?>
<?xml version="1.0" encoding="utf-8"?>
<bookstore><book bid='b0001'><title>天龙八部</title><intro>人生太苦了</intro></book></bookstore>

API最简单了,基本上照着开发文档写就行了。

Ajax默认无法跨域。最新标准可以,但需要对方允许。

取后台数据:

1
2
3
4
5
6
7
8
9
10
11
xhr.onreadystatechange = function(){
if(this.readyState == 4){ //this即xhr对象
// alert(this.responseXML);
var xmldom = this.responseXML;
var book = xmldom.getElementsByTagName('book')['0'];
var title = book.firstChild.firstChild.wholeText;
var intro = book.lastChild.firstChild.wholeText;
document.getElementById('btitle').value = title;
document.getElementById('bintro').value = intro;
}
}

在后端生成格式化文件,拼接成HTML或者json文档,操作DOM,生成新的HTML页面。

返回值类型:大的方向可以分为普通文本和xml文档。
普通文本返回类型又分为:

  • 返回简短的标志字符串,如0,1,OK
  • 后台返回大段的HTML代码,直接innerHTML到前端页面
  • json格式,再由js解析

很多类型,除了HTML5新标准返回的是json,本是文本,只不过符合某些规律,例如json格式。

eval将普通文本转化成js对象[object: Object]。
自己手写的后台数据:

1
2
3
<?php  //code  ?>
{name: 'linking', sex: 'male'}
?>

前端解析:

1
2
var linking = eval('(' + this.responseText + ')');
alert(linking.name);

如果是PHP后台获取数据:

1
2
$book = array('title' => '天龙八部', 'intro' => '人生九苦' );
echo json_encode($book) ;

JSONP解决跨域问题

JSONP不是JSON,只是一种协议,还未被标准组织规范,大家约定使用返回字符串;不用造对象。

Wikipedia解释:

JSONP(JSON with Padding)是资料格式 JSON 的一种“使用模式”,可以让网页从别的网域要资料。另一个解决这个问题的新方法是跨来源资源共享(CORS)。
由于同源策略,一般来说位于 server1.example.com 的网页无法与不是 server1.example.com 的服务器沟通,而 HTML 的 script 元素是一个例外。利用 script 元素的这个开放策略,网页可以得到从其他来源动态产生的 JSON 资料,而这种使用模式就是所谓的 JSONP。用 JSONP 抓到的资料并不是 JSON,而是任意的 JavaScript,用 JavaScript 直译器执行而不是用 JSON 解析器解析。
padding填充:典型的 JSONP 就是把既有的 JSON API 用函数呼叫包起来以达到跨域存取的解法。
script元素注入:为了要启动一个 JSONP 呼叫(或者说,使用这个模式),你需要一个 script 元素。因此,浏览器必须为每一个 JSONP 要求加(或是重用)一个新的、有所需 src 值的 script 元素到 HTML DOM 里—或者说是“注入”这个元素。浏览器执行该元素,抓取 src 里的 URL,并执行回传的 JavaScript。
也因为这样,JSONP 被称作是一种“让使用者利用 script 元素注入的方式绕开同源策略”的方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function sear(){
//获取将要搜索的内容
var searchtext = document.getElementsByName('searchtext')[0].value;
//Google ajax API 搜索参数,返回json格式,利用回调函数aa解析
var url = 'http://ajax.googleais.com/ajax/services/search/web?v=1.0&q='+ searchtext + '&callback=aa';
//动态创建script标签,加入head,使其以script形式加载进来
var scr = document.createElement('script');
scr.setAttribute('type', 'text/javascript');
scr.setAttribute('src', url);
document.getElementByTagName('head')[0].appendChild(scr);
}
//回调函数,对返回的数据进行处理
function aa(res){
alert(res);
}
  • 本文作者: Linking
  • 本文链接: https://linking.fun/2016/02/28/Ajax系列三-探讨XHR及POST数据/
  • 版权声明: 版权所有,转载请注明出处!
  • ajax
  • cs

扫一扫,分享到微信

HTML5与Ajax上传文件
Ajax系列二-现代化的Ajax
  1. 1. #Ajax系列三-深度探讨XHR及POST数据Ajax异步原理
  2. 2. Ajax返回值之XML类型
  3. 3. JSONP解决跨域问题
© 2015-2026 Linking
GitHub:hexo-theme-yilia-plus by Litten
本站总访问量次 | 本站访客数人
  • 所有文章
  • 外链

tag:

  • weather
  • 需求
  • essay
  • basketball
  • olympic
  • nginx
  • APPScan
  • SQl盲注
  • xss
  • Ajax
  • ajax
  • ai
  • agent
  • openclaw
  • ccf
  • Nginx
  • HTML5
  • html5
  • hmtl5
  • sse
  • JavaScriptCore
  • Oracle
  • operation
  • Linux
  • deploy
  • Mac Office
  • markdown
  • ListView
  • GridView
  • MySQL
  • 慢查询
  • mongodb
  • 转置
  • thought
  • network
  • ubuntu
  • NetworkManager
  • RFKill
  • Netplan
  • avatar
  • cocoa
  • blog
  • Gitalk
  • container
  • macvlan
  • docker
  • oracle
  • cookie
  • patch
  • gitea
  • git
  • iOS
  • https
  • 多线程
  • bundle
  • 兼容性
  • HTTP
  • 绘图
  • cs
  • java
  • 效率
  • 快捷键
  • route
  • nodejs
  • pip
  • arcgis
  • arcgis 建模
  • 标识
  • redis
  • read
  • bookList
  • running
  • showdoc
  • disk
  • unit-test
  • D.Wade
  • thoughts
  • duoduo
  • Python
  • python
  • tomcat
  • 读书节
  • session
  • jdk
  • war
  • 加班
  • Android onclick事件监听
  • 正则
  • 手机品牌匹配
  • ntp
  • OpenLayers
  • Geoserver
  • wechat
  • 微信公众号
  • 爬虫
  • WeChat
  • 张靓颖
  • 动漫
  • vpn
  • PPT
  • MarkDown
  • plan
  • 朱赟
  • 极客时间专栏
  • 极客邦
  • 模块化
  • MVC
  • excel
  • NBA
  • kobe
  • team
  • crawler
  • 进度条
  • ssl
  • book
  • anti-stealing-link
  • Agentic Engineering
  • Vibe Coding
  • Software 3.0
  • Andrej Karpathy
  • LLM
  • Programming

    缺失模块。
    1、请确保node版本大于6.2
    2、在博客根目录(注意不是yilia-plus根目录)执行以下命令:
    npm i hexo-generator-json-content --save

    3、在根目录_config.yml里添加配置:

      jsonContent:
        meta: false
        pages: false
        posts:
          title: true
          date: true
          path: true
          text: false
          raw: false
          content: false
          slug: false
          updated: false
          comments: false
          link: false
          permalink: false
          excerpt: false
          categories: false
          tags: true
    

  • GitHub Trending
  • OpenAI ChatGPT
  • Gitee码云
  • 简书
  • CSDN