jQuery 中的 AJAX POST 请求
今天的文章将介绍 jQuery 中的 AJAX POST
请求。
jQuery 中的 AJAX POST
请求
jQuery 的 AJAX POST
请求执行异步 HTTP (AJAX) 请求。
语法:
jQuery.ajax(url[, settings])
jQuery.ajax([settings])
$.ajax()
函数是所有通过 jQuery 分派的 AJAX 请求的基础。一次调用这个特性通常是没有用的,因为有许多更高级别的选项,如 $.Get()
和 .load()
可用且更易于应用。
如果更少,则需要常用选项,尽管可以更灵活地使用 $.ajax()
。
从 jQuery 1.5 开始,通过 $.ajax()
返回的 jQuery XMLHttpRequest
(jqXHR
) 对象是浏览器本地 XMLHttpRequest
元素的超集。例如,它包含 responseText
和 responseXML
房屋,以及 getResponseHeader()
技术。
虽然交付机制与 XMLHttpRequest
不同(例如,JSONP
请求的脚本标签),jqXHR
项在可行的情况下模拟原生 XHR 功能。
从 jQuery 1.5.1 开始,jqXHR
对象还带有 overrideMimeType()
方法(它在 jQuery 1.4.X 中也发生了变化,但在 jQuery 1.5 中被暂时删除)。例如,可以在 beforeSend()
回调函数中使用 .overrideMimeType()
技术来更改响应的 Content-Type 标头。
对 $.Ajax()
调用的不同响应在传递给成功处理程序之前要经过特定类型的预处理。可用的信息种类是 text
、HTML
、XML
、JSON
、JSONP
和 script
。
data 选项可以以 key1=value1&key2=value2
形式的查询字符串或 {key1: 'value1', key2: 'value2'}
形式的对象发送数据。
由于浏览器安全限制,大部分 AJAX 请求都属于同源覆盖;该请求无法有效地从不同的域、子域、端口或协议中检索事实。
在 .ajax() 文档中查找更多信息。
让我们通过以下示例来理解它。以下代码不能按原样运行并且没有输出。
必须将其添加到现有代码中才能查看输出。
<form id="myForm">
<label for="name">Name</label>
<input id="name" name="name" type="text" value="Smith" />
<input type="submit" value="Send" />
</form>
$('#myForm').submit(function(event) {
event.preventDefault();
$.ajax({
method: 'POST',
url: '/open/hello-world',
data: {name: 'Smith', location: 'Doe'}
}).done(function(msg) {
alert('Data Saved: ' + msg);
});
})
一旦用户提交了上面示例中的表单,就会使用指定的 URL 和参数将 AJAX 调用发送到服务器。当服务器返回成功消息时,你可以在控制台上打印该消息或使用适当的消息通知用户。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
用 jQuery 检查复选框是否被选中
发布时间:2024/03/24 浏览次数:102 分类:JavaScript
-
在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。