Home Web Front-end JS Tutorial jsonp+json implements AJAX cross-domain requests

jsonp+json implements AJAX cross-domain requests

Apr 25, 2018 pm 04:49 PM
ajax javascript

This time I will bring you jsonp json to implement AJAX cross-domain requests. What are the precautions for jsonp json to implement AJAX cross-domain requests? The following is a practical case, let's take a look.

AJAX (Asynchronous JavaScript and XML) is a technology for creating fast, dynamic web pages that exchange data with the server and update parts of it without reloading the entire page. Web pages, ajax uses XMLHttpRequest objects to exchange data with the server in the background. XMLHttpRequest is the basis of AJAX, which allows client-side JavaScript to connect to remote servers through HTTP requests.

However, due to browser restrictions, this method cannot be used for cross-domain access. If this method is used for cross-domain access, security issues will arise. However, we can find that when calling js files across domains on a web page, it will not be restricted by the browser, so we can load the data from the remote server into a js format file, and then use it for the client to call.

JSON (JavaScript Object Notation) is a lightweight text data exchange format that is self-describing and easy to understand. JSON can be parsed using JavaScript , and JSON data can be transmitted using AJAX .

JSON example:

{
 "employees": [
 { "firstName":"Bill" , "lastName":"Gates" },
 { "firstName":"George" , "lastName":"Bush" },
 { "firstName":"Thomas" , "lastName":"Carter" }
 ]
 }
Copy after login

JSON syntax is a subset of JavaScript object notation syntax:

Data is in name/value pairs, data is represented by Comma delimits, curly braces save objects, square brackets save array .

Characteristics of JSON

  • Plain text, easy to pass across platforms

  • Javascript is natively supported, and almost all background languages ​​are supported

  • Using a lightweight text data exchange format, suitable for transmitting on the Internet

  • Smaller, faster, and easier to parse than XML.

Based on these features of JSON, the server can dynamically generate a JSON file, and then load the data required by the client into this file , and then transfer the file back to the client for client use. In order to facilitate the client to use data, an informal transmission protocol JSONP has gradually been formed. One of the key points of this protocol is to allow the user to pass a callback parameter to the server, and then the server returns This callback parameter will be used as the function name to load the JSON data, so that the client can customize its own function to automatically process the returned data.

How to use JSONP

A simple way is to use jQuery:

<!DOCTYPE html>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
 <title>test</title>
 <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.js"></script>
  <script type="text/javascript">
  $(document).ready(function(){ 
   
  $.ajax({
    type: "get",
    async: false,
    url: "http://encounter.christmas023.space/json.php?name=mavis&age=18",
    dataType: "jsonp",
    jsonp: "callback",//传递给请求处理程序或页面的,用以获得jsonp回调函数名的参数名(一般默认为:callback)
    jsonpCallback:"message",//自定义的jsonp回调函数名称,默认为jQuery自动生成的随机函数名,也可以写"?",jQuery会自动为你处理数据
    success: function(json){
     alert('你的名字:' + json.name + ' 年龄: ' + json.age);  
    },
    error: function(){
     alert('fail');
    }
   });
  });
  </script>
</head>
<body>
</body>
</html>
Copy after login
  • type: Request type , GET or POST, the default is GET;

  • async: true (asynchronous) or false (synchronous), By default, it is true. Synchronous requests will lock the browser, and other operations of the user must wait for the request to be completed before they can be executed;

  • url: The address to send the request ( It should be an absolute address when making cross-domain requests);

  • dataType: Specify the data type returned by the server;

  • jsonpCallback: Custom JSONP callback function name;

  • success: Callback function after the request is successful;

  • error: This method is called when the request fails.

Run result:

Data type returned by the server:

Return a callback function with the specified function name message, and the data wrapped in the function is in JSON format.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Recommended reading:

How can Jsonp solve ajax cross-domain

Calling ajax in jQuery to achieve asynchronous implementation

The above is the detailed content of jsonp+json implements AJAX cross-domain requests. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

Asynchronous data exchange using Ajax functions Asynchronous data exchange using Ajax functions Jan 26, 2024 am 09:41 AM

How to use Ajax functions to achieve asynchronous data interaction With the development of the Internet and Web technology, data interaction between the front end and the back end has become very important. Traditional data interaction methods, such as page refresh and form submission, can no longer meet user needs. Ajax (Asynchronous JavaScript and XML) has become an important tool for asynchronous data interaction. Ajax enables the web to use JavaScript and the XMLHttpRequest object

See all articles