search
HomeCommon ProblemHow to write ajax
How to write ajaxMay 08, 2019 am 11:54 AM

ajax standard writing example:

How to write ajax

$.ajax({
    url:"http://www.microsoft.com",    //请求的url地址
    dataType:"json",   //返回格式为json
    async:true,//请求是否异步,默认为异步,这也是ajax重要特性
    data:{"id":"value"},    //参数值
    type:"GET",   //请求方式
    beforeSend:function(){
        //请求前的处理
    },
    success:function(req){
        //请求成功时处理
    },
    complete:function(){
        //请求完成的处理
    },
    error:function(){
        //请求出错处理
    }
});
 
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",function(req){
    $.each(req.items,function(i, item){
        if(i == vnum){
            $("<img  src="/static/imghwm/default1.png"  data-src="" + item.media.m + "  class="lazy"   + item.media.m + "" title="" + item.title + "" / alt="How to write ajax" >").appendTo("#showjson");
        }
    });
});

AJAX detailed parameter introduction:

1.url:
Requires a String type parameter, (default is the current page address) the address to which the request is sent.

2.type:
Requires parameters of String type, and the request method (post or get) defaults to get. Note that other http request methods such as put and delete can also be used, but are only supported by some browsers.

3.timeout:
Requires a parameter of type Number and sets the request timeout (milliseconds). This setting will override the global setting of the $.ajaxSetup() method.

4.async:
Requires Boolean type parameters, the default setting is true, and all requests are asynchronous requests. If you need to send synchronous requests, set this option to false. Note that a synchronous request will lock the browser, and the user must wait for the request to complete before other operations can be performed.

5.cache:
Requires a Boolean type parameter, the default is true (when dataType is script, the default is false), setting it to false will not load the request information from the browser cache.

6.data:
Requires parameters of type Object or String, data sent to the server. If it is not a string, it will be automatically converted to string format. The get request will be appended to the url. To prevent this automatic conversion, check the processData option. The object must be in key/value format, for example {foo1:"bar1",foo2:"bar2"} is converted to &foo1=bar1&foo2=bar2. If it is an array, JQuery will automatically assign the same name to different values. For example, {foo:["bar1","bar2"]} is converted to &foo=bar1&foo=bar2.

7.dataType:
Requires parameters of String type, expected data type returned by the server. If not specified, JQuery will automatically return responseXML or responseText based on the http package mime information and pass it as a callback function parameter. The available types are as follows:
xml: Returns an XML document that can be processed with JQuery.
html: Returns plain text HTML information; the included script tag will be executed when inserted into the DOM.
script: Returns plain text JavaScript code. Results are not automatically cached. Unless cache parameters are set. Note that when making remote requests (not under the same domain), all post requests will be converted into get requests.
json: Return JSON data.
jsonp: JSONP format. When calling a function using the SONP form, such as myurl?callback=?, JQuery will automatically replace the last "?" with the correct function name to execute the callback function.
text: Returns a plain text string.

8.beforeSend:
Requires parameters of Function type. You can modify the function of the XMLHttpRequest object before sending the request, such as adding a custom HTTP header. If false is returned in beforeSend, this ajax request can be canceled. The XMLHttpRequest object is the only parameter.
             function(XMLHttpRequest){
                                                                                                                                                                                               ## The callback function (called when the request succeeds or fails). Parameters: XMLHttpRequest object and a string describing the successful request type.
Function (xmlhttpRequest, TextStatus) {
this; // Call the options parameter passed during the Ajax request
#}
## 10.Success: The request is the parameter of the Function type, and the request is successful. The callback function called later has two parameters.
           (1) Data returned by the server and processed according to the dataType parameter.
(2) Describe the string of the state.

FUNCTION (Data, TextStatus) {

// Data may be XMLDOC, JSONOBJ, HTML, Text, etc.
#11.error:
Requires parameters of Function type, the function to be called when the request fails. This function has three parameters, namely XMLHttpRequest object, error message, and captured error object (optional). The ajax event function is as follows:
function(XMLHttpRequest, textStatus, errorThrown){
Normally only one of textStatus and errorThrown contains information
this; //The options parameters passed when calling this ajax request
}

12.contentType:
Requires parameters of String type. When sending information to the server, the content encoding type defaults to "application/x-www-form-urlencoded". This default value is suitable for most applications.

13.dataFilter:
Requires parameters of Function type, a function that preprocesses the original data returned by Ajax. Provide two parameters: data and type. data is the original data returned by Ajax, and type is the dataType parameter provided when calling jQuery.ajax. The value returned by the function will be further processed by jQuery.
           function(data, type)                                                                                                                                                                                                                                                                                      . Function to preprocess the raw data returned by Ajax. Provide two parameters: data and type. data is the original data returned by Ajax, and type is the dataType parameter provided when calling jQuery.ajax. The value returned by the function will be further processed by jQuery.
            function(data, type){
                                                                                                                                                                                             Default is true. Indicates whether to trigger the global ajax event. Setting to false will not trigger global ajax events, ajaxStart or ajaxStop can be used to control various ajax events.

16.ifModified:

Requires parameters of Boolean type, defaults to false. Only get new data when server data changes. The basis for determining server data changes is the Last-Modified header information. The default value is false, which means header information is ignored.

17.jsonp:
Requires parameters of String type to rewrite the name of the callback function in a jsonp request. This value is used to replace the "callback" part of the URL parameter in a GET or POST request such as "callback=?". For example, {jsonp:'onJsonPLoad'} will cause "onJsonPLoad=?" to be passed to the server.

18.username:

Requires a String type parameter, used to respond to the username of the HTTP access authentication request.


19.password:

Requires a String type parameter, which is the password used to respond to the HTTP access authentication request.


20.processData:

Requires a Boolean type parameter, the default is true. By default, the data sent will be converted to an object (technically not a string) to match the default content type "application/x-www-form-urlencoded". If you want to send DOM tree information or other information that you do not want to convert, set it to false.


21.scriptCharset:

is required to be a parameter of String type. It will be used to force the character set to be modified only when the dataType is "jsonp" or "script" during the request, and the type is GET. (charset). Usually used when the local and remote content encodings are different.

The above is the detailed content of How to write ajax. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
deepseek web version official entrancedeepseek web version official entranceMar 12, 2025 pm 01:42 PM

The domestic AI dark horse DeepSeek has risen strongly, shocking the global AI industry! This Chinese artificial intelligence company, which has only been established for a year and a half, has won wide praise from global users for its free and open source mockups, DeepSeek-V3 and DeepSeek-R1. DeepSeek-R1 is now fully launched, with performance comparable to the official version of OpenAIo1! You can experience its powerful functions on the web page, APP and API interface. Download method: Supports iOS and Android systems, users can download it through the app store; the web version has also been officially opened! DeepSeek web version official entrance: ht

In-depth search deepseek official website entranceIn-depth search deepseek official website entranceMar 12, 2025 pm 01:33 PM

At the beginning of 2025, domestic AI "deepseek" made a stunning debut! This free and open source AI model has a performance comparable to the official version of OpenAI's o1, and has been fully launched on the web side, APP and API, supporting multi-terminal use of iOS, Android and web versions. In-depth search of deepseek official website and usage guide: official website address: https://www.deepseek.com/Using steps for web version: Click the link above to enter deepseek official website. Click the "Start Conversation" button on the homepage. For the first use, you need to log in with your mobile phone verification code. After logging in, you can enter the dialogue interface. deepseek is powerful, can write code, read file, and create code

How to solve the problem of busy servers for deepseekHow to solve the problem of busy servers for deepseekMar 12, 2025 pm 01:39 PM

DeepSeek: How to deal with the popular AI that is congested with servers? As a hot AI in 2025, DeepSeek is free and open source and has a performance comparable to the official version of OpenAIo1, which shows its popularity. However, high concurrency also brings the problem of server busyness. This article will analyze the reasons and provide coping strategies. DeepSeek web version entrance: https://www.deepseek.com/DeepSeek server busy reason: High concurrent access: DeepSeek's free and powerful features attract a large number of users to use at the same time, resulting in excessive server load. Cyber ​​Attack: It is reported that DeepSeek has an impact on the US financial industry.

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software