jquery 示例_最好的jQuery示例

jquery 示例

jQuery is the most widely-used JavaScript library, and is used in more than half of all major websites. It's motto is "write less, do more...!"

jQuery是使用最广泛JavaScript库,并在所有主要网站的一半以上中使用。 座右铭是“少写,多做...!”

jQuery makes web development easier to use by providing a number of 'helper' functions. These help developers to quickly write DOM (Document Object Model) interactions without needing to manually write as much JavaScript themselves.

jQuery通过提供许多“帮助”功能使Web开发更易于使用。 这些功能可帮助开发人员快速编写DOM(文档对象模型)交互,而无需自己手动编写太多JavaScript。

jQuery adds a global variable with all of the libraries methods attached. The naming convention is to have this global variable as $. by typing in $. you have all the jQuery methods at your disposal.

jQuery添加了一个附加了所有库方法的全局变量。 命名约定是将此全局变量设为$ 。 通过输入$. 您可以使用所有jQuery方法。

入门 (Getting Started)

There are two main ways to start using jQuery:

开始使用jQuery的主要方法有两种:

  • Include jQuery locally: Download the jQuery library from jquery.com and include it in your HTML code.

    在本地包含jQuery :从jquery.com下载jQuery库并将其包含在您HTML代码中。

  • Use a CDN: Link to the jQuery library using a CDN (Content Delivery Network).

    使用CDN :使用CDN(内容交付网络)链接到jQuery库。

<head>
  <script src="/jquery/jquery-3.4.1.min.js"></script>
  <script src="js/scripts.js"></script>
</head>
<head>
  <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="js/scripts.js"></script>
</head>

选择器 (Selectors)

jQuery uses CSS-style selectors to select parts, or elements, of an HTML page. It then lets you do something with the elements using jQuery methods, or functions.

jQuery使用CSS样式选择器选择HTML页面的部分或元素。 然后,您可以使用jQuery方法或函数对元素进行操作。

To use one of these selectors, type a dollar sign and parentheses after it: $(). This is shorthand for the jQuery() function. Inside the parentheses, add the element you want to select. You can use either single- or double-quotes. After this, add a dot after the parentheses and the method you want to use.

要使用这些选择器之一,请在其后键入美元符号和括号: $() 。 这是jQuery()函数的简写。 在括号内,添加要选择的元素。 您可以使用单引号或双引号。 此后,在圆括号和要使用的方法后面添加一个点。

In jQuery, the class and ID selectors are like those in CSS.

在jQuery中,类和ID选择器类似于CSS中的选择器。

Here's an example of a jQuery method that selects all paragraph elements, and adds a class of "selected" to them:

这是一个jQuery方法的示例,该方法选择所有段落元素,并向其中添加“已选择”类:

<p>This is a paragraph selected by a jQuery method.</p>
<p>This is also a paragraph selected by a jQuery method.</p>

$("p").addClass("selected");

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot (.) and the class name. If you want to select elements with a certain ID, use the hash symbol (#) and the ID name. Note that HTML is not case-sensitive, therefore it is best practice to keep HTML markup and CSS selectors lowercase.

在jQuery中,类和ID选择器与CSS中的相同。 如果要选择具有特定类的元素,请使用点( . )和类名称。 如果要选择具有特定ID的元素,请使用井号( # )和ID名称。 请注意,HTML不区分大小写,因此,最佳做法是将HTML标记和CSS选择器保持小写。

按班级选择 (Selecting by class)

If you want to select elements with a certain class, use a dot (.) and the class name.

如果要选择具有特定类的元素,请使用点(。)和类名称。

<p class="pWithClass">Paragraph with a class.</p>
$(".pWithClass").css("color", "blue"); // colors the text blue

You can also use the class selector in combination with a tag name to be more specific.

您还可以将类选择器与标记名称结合使用,以更加具体。

<ul class="wishList">My Wish List</ul>`<br>
$("ul.wishList").append("<li>New blender</li>");

通过ID选择 (Selecting by ID)

If you want to select elements with a certain ID value, use the hash symbol (#) and the ID name.

如果要选择具有特定ID值的元素,请使用井号(#)和ID名称。

<li id="liWithID">List item with an ID.</li>
$("#liWithID").replaceWith("<p>Socks</p>");

As with the class selector, this can also be used in combination with a tag name.

与类选择器一样,它也可以与标签名结合使用。

<h1 id="headline">News Headline</h1>
$("h1#headline").css("font-size", "2em");

按属性值选择 (Selecting by attribute value)

If you want to select elements with a certain attribute, use ([attributeName="value"]).

如果要选择具有特定属性的元素,请使用([attributeName="value"])

<input name="myInput" />
$("[name='myInput']").value("Test"); // sets input value to "Test"

You can also use the attribute selector in combination with a tag name to be more specific.

您还可以将属性选择器与标签名称结合使用,以更加具体。

<input name="myElement" />`<br>
<button name="myElement">Button</button>
$("input[name='myElement']").remove(); // removes the input field not the button

充当过滤器的选择器 (Selectors that act as filters)

There are also selectors that act as filters - they will usually start with colons. For example, the :first selector selects the element that is the first child of its parent. Here's an example of an unordered list with some list items. The jQuery selector below the list selects the first <li> element in the list--the "One" list item--and then uses the .css method to turn the text green.

还有一些选择器充当过滤器-它们通常以冒号开头。 例如, :first选择器选择作为其父级的第一个子级的元素。 这是带有一些列表项的无序列表的示例。 列表下方的jQuery选择器选择列表中的第一个<li>元素(“一个”列表项),然后使用.css方法将文本变为绿色。

<ul>
      <li>One</li>
      <li>Two</li>
      <li>Three</li>
   </ul>
$("li:first").css("color", "green");

属性选择器 (Attribute Selector)

There are selectors that return elements which matches certain combinations of Attributes like Attribute contains, Attribute ends with, Attribute starts with etc. Here's an example of an unordered list with some list items. The jQuery selector below the list selects the <li> element in the list--the "One" list item as it has data* attribute as "India" as its value--and then uses the .css method to turn the text green.

有一些选择器返回与某些属性组合匹配的元素,例如Attribute containsAttribute结束Attribute开头等。这是带有一些列表项的无序列表的示例。 列表下方的jQuery选择器选择列表中的<li>元素(“ One”列表项,因为它的data*属性为"India"作为其值),然后使用.css方法将文本变为绿色。

<ul>
      <li data-country="India">Mumbai</li>
      <li data-country="China">Beijing</li>
      <li data-country="United States">New York</li>
   </ul>
$("li[data-country='India']").css("color", "green");

Another filtering selector, :contains(text), selects elements that have a certain text. Place the text you want to match in the parentheses. Here's an example with two paragraphs. The jQuery selector takes the word "Moto" and changes its color to yellow.

另一个过滤选择器:contains(text) ,选择具有特定文本的元素。 将要匹配的文本放在括号中。 这是一个包含两个段落的示例。 jQuery选择器使用单词“ Moto”,并将其颜色更改为黄色。

<p>Hello</p>
    <p>World</p>
$("p:contains('World')").css("color", "yellow");

Similarly, the :last selector selects the element that is the last child of its parent. The jQuery selector below selects the last <li> element in the list--the "Three" list item--and then uses the .css method to turn the text yellow.

同样, :last选择器选择作为其父级的最后一个子级的元素。 下面的jQuery选择器选择列表中的最后一个<li>元素(“三”列表项),然后使用.css方法将文本变为黄色。

$("li:last").css("color", "yellow");

$("li:last").css("color", "yellow");

Note: In the jQuery selector, World is in single-quotes because it is already inside a pair of double-quotes. Always use single-quotes inside double-quotes to avoid unintentionally ending a string.

注意:在jQuery选择器中, World用单引号引起来,因为它已经在一对双引号内。 始终在双引号内使用单引号,以避免无意中结束字符串。

多个选择器 (Multiple Selectors)

In jQuery, you can use multiple selectors to apply the same changes to more than one element, using a single line of code. You do this by separating the different ids with a comma. For example, if you want to set the background color of three elements with ids cat,dog,and rat respectively to red, simply do:

在jQuery中,您可以使用多个选择器通过一行代码将相同的更改应用于一个以上的元素。 您可以通过用逗号分隔不同的ID来做到这一点。 例如,如果要将ID为cat,dog和rat的三个元素的背景色设置为红色,只需执行以下操作:

$("#cat,#dog,#rat").css("background-color","red");

HTML方法 (HTML Method)

The jQuery .html() method gets the content of a HTML element or sets the content of an HTML element.

jQuery .html()方法获取HTML元素的内容或设置HTML元素的内容。

得到 (Getting)

To return the content of a HTML element, use this syntax:

要返回HTML元素的内容,请使用以下语法:

$('selector').html();

For example:

例如:

$('#example').html();

设置 (Setting)

To set the content of a HTML element, use this syntax:

要设置HTML元素的内容,请使用以下语法:

$('selector').html(content);

For example:

例如:

$('p').html('Hello World!');

That will set the content of all of the <p> elements to Hello World!

这会将所有<p>元素的内容设置为Hello World!

警告 (Warning)

.html() method is used to set the element's content in HTML format. This may be dangerous if the content is provided by user. Consider using .text() method instead if you need to set non-HTML strings as content.

.html()方法用于以HTML格式设置元素的内容。 如果内容由用户提供,则可能很危险。 如果需要将非HTML字符串设置为内容,请考虑改用.text()方法。

CSS方法 (CSS Method)

The jQuery .css() method gets the value of a computed style property for the first element in the set of matched elements or set one or more CSS properties for every matched element.

jQuery .css()方法获取匹配元素集中第一个元素的计算样式属性值,或者为每个匹配元素设置一个或多个CSS属性。

得到 (Getting)

To return the value of a specified CSS property, use the following syntax:

要返回指定CSS属性的值,请使用以下语法:

$(selector).css(propertyName);

Example:

例:

$('#element').css('background');

Note: Here we can use any css selector eg: element(HTML Tag selector), .element(Class Selector), #element(ID selector).

注意:这里我们可以使用任何CSS选择器,例如:element(HTML标签选择器)、. element(类选择器),#element(ID选择器)。

设置 (Setting)

To set a specified CSS property, use the following syntax:

要设置指定CSS属性,请使用以下语法:

$(selector).css(propertyName,value);

Example:

例:

$('#element').css('background','red');

To set multiple CSS properties, you'll have to use the object literal syntax like this:

要设置多个CSS属性,您必须使用对象文字语法,如下所示:

$('#element').css({
        'background': 'gray',
        'color': 'white'
    });

If you want to change a property labeled with more than one word, refer to this example:

如果要更改标记有多个单词的属性,请参考以下示例:

To change background-color of an element

更改元素的background-color

$('#element').css('background-color', 'gray');

点击方式 (Click Method)

The jQuery Click method triggers a function when an element is clicked. The function is known as a "handler" because it handles the click event. Functions can impact the HTML element that is bound to the click using the jQuery Click method, or they can change something else entirely. The most-used form is:

当单击元素时,jQuery Click方法触发一个函数。 该函数称为“处理程序”,因为它处理click事件。 函数可以影响使用jQuery Click方法绑定到单击HTML元素,或者它们可以完全更改其他内容。 最常用的形式是:

$("#clickMe").click(handler)

The click method takes the handler function as an argument and executes it every time the element #clickMe is clicked. The handler function receives a parameter known as an eventObject that can be useful for controlling the action.

click方法将处理函数作为参数,并在每次单击元素#clickMe时执行该方法。 处理程序函数接收一个称为eventObject的参数,该参数可用于控制操作。

例子 (Examples)

This code shows an alert when a user clicks a button:

此代码显示用户单击按钮时的警报:

<button id="alert">Click Here</button>
$("#alert").click(function () {
  alert("Hi! I'm an alert");
});

The eventObject has some built in methods, including preventDefault(), which does exactly what it says - stops the default event of an element. Here we pevent the anchor tag from acting as a link:

eventObject具有一些内置方法,包括preventDefault() ,它完全按照其说的进行操作-停止元素的默认事件。 在这里,我们将锚标记用作链接:

<a id="myLink" href="www.google.com">Link to Google</a>
$("#myLink").click(function (event) {
  event.preventDefault();
});

使用click方法的更多方式 (More ways to play with the click method)

The handler function can also accept additional data in the form of an object:

处理函数还可以接受对象形式的其他数据:

jqueryElement.click(usefulInfo, handler)

The data can be of any type.

数据可以是任何类型。

$("element").click({firstWord: "Hello", secondWord: "World"}, function(event){
    alert(event.data.firstWord);
    alert(event.data.secondWord);
});

Invoking the click method without a handler function triggers a click event:

在没有处理函数的情况下调用click方法会触发click事件:

$("#alert").click(function () {
  alert("Hi! I'm an alert");
});

$("#alert").click();

Now, whenever the page loads, the click event will be triggered when we enter or reload the page, and show the assigned alert.

现在,无论页面何时加载,当我们进入或重新加载页面并显示分配的警报时,都会触发click事件。

Also you should prefer to use .on("click",...) over .click(...) because the former can use less memory and work for dynamically added elements.

另外,您应该更喜欢使用.on("click",...)不是.click(...)因为前者可以使用较少的内存,并且可以动态添加元素。

常见错误 (Common Mistakes)

The click event is only bound to elements currently in the DOM at the time of binding, so any elements added afterwards will not be bound. To bind all elements in the DOM, even if they will be created at a later time, use the .on() method.

click事件仅绑定到绑定时当前在DOM中的元素,因此之后添加的任何元素都不会绑定。 要绑定DOM中的所有元素,即使它们将在以后创建,请使用.on()方法。

For example, this click method example:

例如,此单击方法示例:

$("element").click(function() {
  alert("I've been clicked!");
});

Can be changed to this on method example:

可以在方法示例中更改为此:

$(document).on("click", "element", function() {
  alert("I've been clicked!");
});

从Click事件获取元素 (Getting The Element From A Click event)

This applies to both jQuery and plain JavaScript, but if you set up your event trigger to target a class, you can grab the specific element that triggered the element by using the this keyword.

这适用于jQuery和普通JavaScript,但是如果将事件触发器设置为以类为目标,则可以使用this关键字获取触发该元素的特定元素。

jQuery happens to make it very easy (and multi browser friendly) to traverse the DOM to find that element's parents, siblings, and children, as well.

jQuery碰巧使遍历DOM非常容易(并且对多浏览器友好),从而可以找到该元素的父母,兄弟姐妹和孩子。

Let's say I have a table full of buttons and I want to target the row that button is in, I can simply wrap this in a jQuery selector and then get its parent and its parent's parent like so:

比方说,我有一个完整的按钮表,我想指定的一行按钮是,我可以简单地包裹this在jQuery选择,然后获取其parent及其母公司的parent ,如下所示:

$( document ).on("click", ".myCustomBtnClassInATable", function () {
    var myTableCell = $(this).parent();
    var myTableRow = myTableCell.parent();
    var myTableBody = myTableRow.parent();
    var myTable = myTableBody.parent();
    
    //you can also chain these all together to get what you want in one line
    var myTableBody = $(this).parent().parent().parent();
});

It is also interesting to check out the event data for the click event, which you can grab by passing in any variable name to the function in the click event. You'll most likely see an e or event in most cases:

签出click事件的事件数据也很有趣,您可以通过在click事件中将任何变量名传递给函数来获取。 在大多数情况下,您很可能会看到eevent

$( document ).on("click", ".myCustomBtnClassInATable", function (e) { 
    //find out more information about the event variable in the console
    console.log(e);
});

鼠标按下方法 (Mousedown Method)

The mousedown event occurs when the left mouse button is pressed. To trigger the mousedown event for the selected element, use this syntax: $(selector).mousedown();

当按下鼠标左键时,发生mousedown事件。 要触发所选元素的mousedown事件,请使用以下语法: $(selector).mousedown();

Most of the time, however, the mousedown method is used with a function attached to the mousedown event. Here's the syntax: $(selector).mousedown(function); For example:

但是,大多数情况下,mousedown方法与mousedown事件附带的函数一起使用。 语法如下: $(selector).mousedown(function); 例如:

$(#example).mousedown(function(){
   alert("Example was clicked");
});

That code will make the page alert "Example was clicked" when #example is clicked.

当单击#example时,该代码将使页面警报“单击了Example”。

悬停方法 (Hover Method)

The jquery hover method is a combination of the mouseenter and mouseleave events. The syntax is this:

jQuery悬停方法是mouseentermouseleave事件的组合。 语法是这样的:

$(selector).hover(inFunction, outFunction);

The first function, inFunction, will run when the mouseenter event occurs. The second function is optional, but will run when the mouseleave event occurs. If only one function is specified, the other function will run for both the mouseenter and mouseleave events. Below is a more specific example.

第一个功能,inFunction,当将要运行mouseenter事件发生。 第二个函数是可选的,但是将在发生mouseleave事件时运行。 如果仅指定一个功能,则将为mouseentermouseleave事件运行另一个功能。 下面是一个更具体的示例。

$("p").hover(function(){
    $(this).css("background-color", "yellow");
}, function(){
    $(this).css("background-color", "pink");
});

So this means that hover on paragraph will change its background color to yellow and the opposite will change back to pink.

因此,这意味着将鼠标悬停在段落上会将其背景颜色更改为黄色,而将相反的颜色更改回粉红色。

动画方法 (Animate Method)

jQuery's animate method makes it easy to create simple animations using only a few lines of code. The basic structure is as following:

jQuery的动画方法使仅使用几行代码即可轻松创建简单的动画。 基本结构如下:

$(".selector").animate(properties, duration, callbackFunction());

For the properties argument, you need to pass a javascript object with the CSS properties you want to animate as keys and the values you want to animate to as values. For the duration, you need to input the amount of time in milliseconds the animation should take. The callbackFunction() is executed once the animation has finished.

对于properties参数,您需要传递一个JavaScript对象,该JavaScript对象具有要作为键进行动画处理CSS属性,并将要作为其动画处理的值作为值。 对于duration ,您需要输入动画应花费的时间(以毫秒为单位)。 动画完成后,将执行callbackFunction()

(Example)

A simple example would look like this:

一个简单的示例如下所示:

$(".awesome-animation").animate({
	opacity: 1,
	bottom: += 15
}, 1000, function() {
	$(".different-element").hide();
});

隐藏方法 (Hide Method)

In its simplest form, .hide() hides the matched element immediately, with no animation. For example:

.hide()以其最简单的形式立即隐藏匹配的元素,没有动画。 例如:

$(".myclass").hide()

will hide all the elements whose class is myclass. Any jQuery selector can be used.

将隐藏所有类为myclass的元素。 可以使用任何jQuery选择器。

.hide()作为动画方法 (.hide() as an animation method)

Thanks to its options, .hide() can animate the width, height, and opacity of the matched elements simultaneously.

由于其选项, .hide()可以同时为匹配元素的宽度,高度和不透明度设置动画。

  • Duration can be provided in milliseconds, or using the literals slow (600 ms) and fast(200ms). for example:

    可以以毫秒为单位提供持续时间,也可以使用文字慢速(600 ms)和快速(200ms)。 例如:
  • A function can be specified to be called once the animation is complete, once per every matched element. This callback is mainly useful for chaining together different animations. For example

    动画完成后,每个匹配的元素都可以指定一个函数来调用。 此回调主要用于将不同的动画链接在一起。 例如
$("#myobject").hide(800)
$("p").hide( "slow", function() {
  $(".titles").hide("fast");
  alert("No more text!");
});

显示方式 (Show Method)

In its simplest form, .show() displays the matched element immediately, with no animation. For example:

.show()以其最简单的形式立即显示匹配的元素,没有动画。 例如:

$(".myclass").show();

will show all the elements whose class is myclass. Any jQuery selector can be used.

将显示所有类为myclass的元素。 可以使用任何jQuery选择器。

However, this method does not override !important in the CSS style, such as display: none !important.

但是,此方法不会覆盖CSS样式中的!important ,例如display: none !important

.show()作为动画方法 (.show() as an animation method)

Thanks to its options, .show() can animate the width, height, and opacity of the matched elements simultaneously.

由于它的选项, .show()可以同时为匹配元素的宽度,高度和不透明度设置动画。

  • Duration can be provided in milliseconds, or using the literals slow (600 ms) and fast(200ms). for example:

    可以以毫秒为单位提供持续时间,也可以使用文字(慢(600毫秒)和快(200毫秒)”来提供。 例如:
  • A function can be specified to be called once the animation is complete, once per every matched element. for example

    动画完成后,每个匹配的元素都可以指定一个函数来调用。 例如
$("#myobject").show("slow");
$("#title").show( "slow", function() {
  $("p").show("fast");
});

jQuery Toggle方法 (jQuery Toggle method)

To show / hide elements you can use toggle() method. If element is hidden toggle() will show it and vice versa. Usage:

要显示/隐藏元素,可以使用toggle()方法。 如果元素被隐藏,则toggle()将显示它,反之亦然。 用法:

$(".myclass").toggle()

向下滑动方法 (Slide Down method)

This method animates the height of the matched elements. This causes lower parts of the page to slide down, making way for the revealed items. Usage:

此方法可对匹配元素的高度进行动画处理。 这会使页面的下部向下滑动,为显示的项目腾出空间。 用法:

$(".myclass").slideDown(); //will expand the element with the identifier myclass for 400 ms.
$(".myclass").slideDown(1000); //will expand the element with the identifier myclass for 1000 ms.
$(".myclass").slideDown("slow"); //will expand the element with the identifier myclass for 600 ms.
$(".myclass").slideDown("fast"); //will expand the element with the identifier myclass for 200 ms.

加载方式 (Load Method)

The load() method loads data from a server and puts the returned data into the selected element.

load()方法从服务器加载数据,并将返回的数据放入选定的元素。

Note: There is also a jQuery Event method called load. Which one is called, depends on the parameters.

注意:还有一个称为Load的jQuery Event方法。 哪个被调用取决于参数。

(Example)

$("button").click(function(){
    $("#div1").load("demo_test.txt");
});

链式 (Chaining)

jQuery chaining allows you to execute multiple methods on the same jQuery selection, all on a single line.

jQuery链允许您在同一jQuery选择上执行多个方法,所有这些都在一行上。

Chaining allows us to turn multi-line statements:

链接使我们能够转换多行语句:

$('#someElement').removeClass('classA');
$('#someElement').addClass('classB');

Into a single statement:

变成单个语句:

$('#someElement').removeClass('classA').addClass('classB');

Ajax获取方法 (Ajax Get Method)

Sends an asynchronous http GET request to load data from the server. Its general form is:

发送异步http GET请求以从服务器加载数据。 其一般形式为:

jQuery.get( url [, data ] [, success ] [, dataType ] )
  • url: The only mandatory parameter. This string contains the address to which to send the request. The returned data will be ignored if no other parameter is specified.

    url :唯一的必需参数。 此字符串包含将请求发送到的地址。 如果未指定其他参数,则将忽略返回的数据。

  • data: A plain object or string sent to the server with the request.

    data :与请求一起发送到服务器的普通对象或字符串。

  • success: A callback function executed if the request succeeds. It takes as an argument the returned data. It is also passed the text status of the response.

    success :如果请求成功执行的回调函数。 它以返回的数据作为参数。 它还传递了响应的文本状态。

  • dataType: The type of data expected from the server. The default is Intelligent Guess (xml, json, script, text, html). If this parameter is provided, the success callback also must be provided.

    dataType :服务器期望的数据类型。 默认值为Intelligent Guess(xml,json,脚本,文本,html)。 如果提供此参数,则还必须提供成功回调。

例子 (Examples)

Request resource.json from the server, send additional data, and ignore the returned result:

从服务器请求resource.json ,发送其他数据,并忽略返回的结果:

$.get('http://example.com/resource.json', {category:'client', type:'premium'});

Request resource.json from the server, send additional data, and handle the returned response (json format):

从服务器请求resource.json ,发送其他数据,并处理返回的响应(json格式):

$.get('http://example.com/resource.json', {category:'client', type:'premium'}, function(response) {
     alert("success");
     $("#mypar").html(response.amount);
});

However, $.get doesn't provide any way to handle error.

但是, $.get没有提供任何处理错误的方法。

The above example (with error handling) can also be written as:

上面的示例(带有错误处理)也可以写成:

$.get('http://example.com/resource.json', {category:'client', type:'premium'})
     .done(function(response) {
           alert("success");
           $("#mypar").html(response.amount);
     })
     .fail(function(error) {
           alert("error");
           $("#mypar").html(error.statusText);
     });

等同于Ajax GET (Ajax GET Equivalent)

$.get( url [, data ] [, success ] [, dataType ] ) is a shorthand Ajax function, equivalent to:

$.get( url [, data ] [, success ] [, dataType ] )是Ajax的简写功能,等效于:

$.ajax({
     url: url,
     data: data,
     success: success,
     dataType: dataType
});

Ajax Post方法 (Ajax Post Method)

Sends an asynchronous http POST request to load data from the server. Its general form is:

发送异步http POST请求以从服务器加载数据。 其一般形式为:

jQuery.post( url [, data ] [, success ] [, dataType ] )
  • url : This is the only mandatory parameter. This string contains the adress to which to send the request. The returned data will be ignored if no other parameter is specified

    url:这是唯一的必需参数。 此字符串包含向其发送请求的地址。 如果未指定其他参数,则将忽略返回的数据
  • data : A plain object or string that is sent to the server with the request.

    data:与请求一起发送到服务器的普通对象或字符串。
  • success : A callback function that is executed if the request succeeds. It takes as an argument the returned data. It is also passed the text status of the response.

    success:如果请求成功执行的回调函数。 它以返回的数据作为参数。 它还传递了响应的文本状态。
  • dataType : The type of data expected from the server. The default is Intelligent Guess (xml, json, script, text, html). if this parameter is provided, then the success callback must be provided as well.

    dataType:服务器期望的数据类型。 默认值为Intelligent Guess(xml,json,脚本,文本,html)。 如果提供了此参数,则还必须提供成功回调。
例子 (Examples)
$.post('http://example.com/form.php', {category:'client', type:'premium'});

requests form.php from the server, sending additional data and ignoring the returned result

从服务器请求form.php ,发送其他数据并忽略返回的结果

$.post('http://example.com/form.php', {category:'client', type:'premium'}, function(response){ 
      alert("success");
      $("#mypar").html(response.amount);
});

requests form.php from the server, sending additional data and handling the returned response (json format). This example can be written in this format:

从服务器请求form.php ,发送其他数据并处理返回的响应(json格式)。 该示例可以用以下格式编写:

$.post('http://example.com/form.php', {category:'client', type:'premium'}).done(function(response){
      alert("success");
      $("#mypar").html(response.amount);
});

The following example posts a form using Ajax and put results in a div

以下示例使用Ajax发布表单并将结果放入div中

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.post demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<form action="/" id="searchForm">
  <input type="text" name="s" placeholder="Search...">
  <input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
 
<script>
// Attach a submit handler to the form
$( "#searchForm" ).submit(function( event ) {
 
  // Stop form from submitting normally
  event.preventDefault();
 
  // Get some values from elements on the page:
  var $form = $( this ),
    term = $form.find( "input[name='s']" ).val(),
    url = $form.attr( "action" );
 
  // Send the data using post
  var posting = $.post( url, { s: term } );
 
  // Put the results in a div
  posting.done(function( data ) {
    var content = $( data ).find( "#content" );
    $( "#result" ).empty().append( content );
  });
});
</script>
 
</body>
</html>

The following example use the github api to fetch the list of repositories of a user using jQuery.ajax() and put results in a div

以下示例使用github API使用jQuery.ajax()获取用户的存储库列表,并将结果放入div中

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery Get demo</title>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<form id="userForm">
  <input type="text" name="username" placeholder="Enter gitHub User name">
  <input type="submit" value="Search">
</form>
<!-- the result of the search will be rendered inside this div -->
<div id="result"></div>
 
<script>
// Attach a submit handler to the form
$( "#userForm" ).submit(function( event ) {
 
  // Stop form from submitting normally
  event.preventDefault();
 
  // Get some values from elements on the page:
  var $form = $( this ),
    username = $form.find( "input[name='username']" ).val(),
    url = "https://api.github.com/users/"+username+"/repos";
 
  // Send the data using post
  var posting = $.post( url, { s: term } );
 
  //Ajax Function to send a get request
  $.ajax({
    type: "GET",
    url: url,
    dataType:"jsonp"
    success: function(response){
        //if request if made successfully then the response represent the data

        $( "#result" ).empty().append( response );
    }
  });
  
});
</script>
 
</body>
</html>

等效于Ajax POST (Ajax POST Equivalent)

$.post( url [, data ] [, success ] [, dataType ] ) is a shorthand Ajax function, equivalent to:

$.post( url [, data ] [, success ] [, dataType ] )是Ajax的简写功能,等效于:

$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

翻译自: https://www.freecodecamp.org/news/the-best-jquery-examples/

jquery 示例

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值