search
HomeWeb Front-endJS TutorialImplementation method of jquery's ajax and getJson to obtain json data across domains_jquery

Many developers are using jquery to interact with data on the front-end and server-side, so it is easy to think that using jquery on the front-end can read the data of any site. When I was developing recently, because I had to share data with a project of a third-party company, and because I was considering not occupying much server resources, I decided to read the data directly in HTML instead of transferring it through the server. Then I just encountered the problem of cross-domain access on the browser side.

Cross-domain security restrictions refer to the browser side, and there are no cross-domain security restrictions on the server side.

There are currently two commonly used methods for browser-side cross-domain access:

1. Cross-domain through jQuery’s ajax. This is actually implemented using jsonp.

jsonp is the abbreviation of English json with padding. It allows script tags to be generated on the server side and returned to the client, that is, javascript tags are dynamically generated and data is read through javascript callback.

HTML page side sample code:

Copy code The code is as follows:

//First To introduce the js package of jquery
jQuery(document).ready(function(){
$.ajax({

type: "get", //jquey does not support post cross-domain

async:false,

url: "http://api.taobao.com/apitools/ajax_props.do", //Cross-domain request URL

dataType: "jsonp",

//Parameter name passed to the request handler to obtain the jsonp callback function name (default: callback)

jsonp: "jsoncallback",

//Customized jsonp callback function name, the default is a random function name automatically generated by jQuery

jsonpCallback:"success_jsonpCallback",

//After successfully obtaining the json data on the cross-domain server, this callback function will be dynamically executed

success : function(json){

                        alert(json);
Server-side code is the key point. I initially thought that as long as the client can directly access cross-domain access through jsonp, this is not the case and requires server-side support.



Copy code


The code is as follows:

//Get the name of the callback function based on the parameter name of the jsonp callback function specified in HTML
//The value of callbackName is actually: success_jsonpCallback

String callbackName = (String)request.getAttribute("jsoncallback");

//Simple simulation of a json string, you can actually use Google's gson for conversion, and the number of times is through string splicing

//{"name":"Zhang San","age":28}

//It is to escape the " sign

String jsonStr = "{"name":"Zhang San","age":28}";

//The final returned data is: success_jsonpCallback({"name":"Zhang San","age":28})

String renderStr = callbackName "(" jsonStr ")";

response.setContentType("text/plain;charset=UTF-8");

response.getWriter().write(renderStr);

}


Principle of jsonp:

First register a callback (such as: 'jsoncallback') on the client side, and then pass the callback name (such as: success_jsonpCallback) to the corresponding processing function on the server side.

The server first generates the json data that needs to be returned to the client. Then use javascript syntax to generate a function. The function name is the value of the passed parameter (jsoncallback) (success_jsonpCallback).

Finally, the json data is placed directly into the function as a parameter, thus generating a js syntax document and returning it to the client.
The client browser parses the script tag and uses the data returned by the server as a parameter.
passes in the callback function predefined by the client (as encapsulated by the jquery $.ajax() method in the above example success: function (json)).

In fact, cross-domain loading of data is done by dynamically adding scripts. Data cannot be obtained directly, so callback functions need to be used.

2. Use jquery’s getJson to read data across domains

In fact, the basic principle of the getJson method is the same as the way ajax uses jsonp.

GetJson is commonly used in jquery to obtain remote data and return it in json format. The prototype of the function is as follows:

jQuery.getJSON(url,data,success(data,status,xhr))

Parameters Description
url Required. Specifies the URL to which the request will be sent.
data Optional. Specifies the data to be sent to the server with the request.
success(data,status,xhr)
参数 描述
url 必需。规定将请求发送的哪个 URL。
data 可选。规定连同请求发送到服务器的数据。
success(data,status,xhr)

可选。规定当请求成功时运行的函数。

额外的参数:

  • response - 包含来自请求的结果数据
  • status - 包含请求的状态
  • xhr - 包含 XMLHttpRequest 对象
Optional. Specifies a function to run when the request succeeds.

Extra parameters:

  • response - Contains result data from the request
  • status - Contains the status of the request
  • xhr - Contains XMLHttpRequest object
This function is the abbreviated ajax function, which is actually equivalent to: Copy code

The code is as follows:


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


Back to business, let’s look at how to use getJson to obtain data across domains.

HTML page sample code: Copy code

The code is as follows:


$.getJSON( "http://api.taobao.com/apitools/ajax_props.do&jsoncallback=?",
function (data) {
alert(data);
}
);Execution principle:

When sending a request, you need to pass a callback function name to the server. The server gets the callback function name, and then returns the return data to the client in the form of parameters, so that the client can call it.

So the address that sends the request URL must be followed by a parameter like jsoncallback=?. jquery will automatically replace the ? number with the name of the automatically generated callback function.

So the final actual request is:

http://api.taobao.com/apitools/ajax_props.do&jsoncallback=jsonp1322444422697 So I want to compare it with the ajax method, that is, one of the callback functions is an automatically generated function name, and the other is a manually specified function name.
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

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

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.