search
HomeWeb Front-endJS TutorialAjax realizes secondary linkage through XML asynchronous submission

This time I will bring you Ajax to achieve secondary linkage through XML asynchronous submission, and Ajax to achieve secondary linkage through XML asynchronous submission. What are the precautions?. Here is a practical case, let's take a look.

I have written before that the province and city information is obtained from the JavaScript array to achieve secondary linkage, but it seems that there are many needs to obtain information from the database, so it needs to be submitted asynchronously , the idea of ​​partial refresh is implemented to improve user interaction issues

The first method is the xml method

1. First of all, In the JavaScript of the jsp page, this code is universal, so it is placed outside the function and can be used by other functions

var xhr=false;
//创建XMLHttpRequst对象
if(window.XMLHttpRequest)
{
xhr=new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
xhr=false;
}

2. Get the selected province value, And pass the value to the servlet through asynchronous submission

//获取城市的信息
function getCity()
{
//省份下拉框的对象
var provinceobj=document.getElementById("province");
//被选择的省份的索引
var index=provinceobj.selectedIndex;
//被选择的省份的value值
var provincevalue=provinceobj[index].value;
//被选择的省份的text值
var province=provinceobj[index].Text;
alert(provincevalue);
var url="CityServlet";/* post请求不在url上带参数 */
CityServlet?provincevalue="+provincevalue; --%>//get请求在url上带参数
xhr.open("post",url,true);//设置为post提交方式,true表示为异步提交
//post提交方式的时候需要设置提交的编码
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
//当状态改变时,调用callBack_XML来判断是否需要接收数据 
     xhr.onreadystatechange=callBack_XML;//xml方法 
    //通过post提交的时候需要将数据放到send里传到servlet里 
    xhr.send("provincevalue="+provincevalue); 
    //xhr.send(null); 
  }

3. Write the callback functioncallBack_XML(). This function determines when the server responds normally, receives the data and Process

function callBack_XML()//xml方法来获取
{
//城市下拉选择框的对象
var cityobj=document.getElementById("city");
//当请求状态等于4时,相应已完成,可以访问服务器响应并使用它
if(xhr.readyState==4)
{
//当状态为200时意味着,状态正常,未出错
if(xhr.status==200)
{
alert("响应成功");
//获取相应的xml文档
var cityxml=xhr.responseXML;
alert(cityxml);
//获取根元素
var root=cityxml.documentElement;
//获取根元素(city_info)下面的所有city元素
var cities=root.getElementsByTagName("city");
//将下拉框内容清除
cityobj.options.length=1;
for(var i=0;i<cities.length var cityobj.options else alert><p style="text-align: left;"><strong>4. On the servlet page: </strong></p>
<pre class="brush:php;toolbar:false">String provincevalue=request.getParameter("provincevalue");
System.out.println("省份编号:"+provincevalue);
CityService cityservice=CityService.getCityService();
List<city> citylist=cityservice.getCity(provincevalue);
for(int i=0;i<citylist.size system.out.println stringbuffer xml.append>");
xml.append("<city_info>");
for(City c : citylist)
{
xml.append("<city>");
xml.append("<id>"+c.getId()+"</id>");
xml.append("<cityid>"+c.getCityid()+"</cityid>");
xml.append("<cityname>"+c.getCity()+"</cityname>");
xml.append("<province>"+c.getFather()+"</province>");
xml.append("</city>");
}
xml.append("</city_info>");
//设置响应字符集编码,防止中文乱码
response.setCharacterEncoding("utf-8");
response.setContentType("text/xml;charset=utf-8");
//将xml文档写出去
PrintWriter writer=response.getWriter();
//因为只能写字符串,所以toString
writer.write(xml.toString());
writer.flush();
writer.close();
}</citylist.size></city>

This completes the use of xml to implement asynchronous submission and partial refresh to achieve provincial and municipal secondary linkage

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 to implement AJAX queue request (with code)

Forward, backward and refresh of Ajax page How to achieve

The above is the detailed content of Ajax realizes secondary linkage through XML asynchronous submission. 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
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

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

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools