Использование Ajax с XML
Предисловие
В этом руководстве мы увидим, как отправлять данные на сервер с использованием XML и как данные извлекаются с сервера в формате XML. Поскольку XML широко используется в качестве формата данных, стоит научиться отправлять запрос и получать ответ с использованием XML и Ajax. Следующая демоверсия показывает вам конечный продукт, который мы создадим к концу этого урока. Вы предоставляете данные в веб-форму, эти данные отправляются на сервер в формате XML, данные сохраняются с созданием файла XML, а затем принимается ответ в формате XML для визуализации данных в браузере.
Отправить данные на сервер
HTML-код нашей веб-формы
Для упрощения мы не добавили никакой проверки в этой форме.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Send request and receive response using XML</title>
<meta name="description" content="HTML and JavaScript code of example of sending and receiving data using XML">
<link href="../includes/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {padding-top: 40px; padding-left: 25%}
li {list-style: none; margin:5px 0 5px 0; color:#FF0000}
</style>
</head>
<body>
<form class="well-home span6 form-horizontal" name="xml-ajax" id="xml-ajax">
<div class="control-group">
<label class="control-label" for="userid">Userid</label>
<div class="controls">
<input type="text" id="userid" placeholder="Required, 5 to 12 chars">
<li id="msg1"></li>
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="password" placeholder="Required, 7 to 12 chars">
<li id="msg2"></li>
</div>
</div>
<div class="control-group">
<label class="control-label" for="name">Name</label>
<div class="controls">
<input type="text" id="name" placeholder="Required, alphabets & space only">
</div>
</div>
<div class="control-group">
<label class="control-label" for="country">Country</label>
<div class="controls">
<select class="span3">
<option>INDIA</option>
<option>USA</option>
<option>UK</option>
<option>CANADA</option>
<option>FRANCE</option>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="zip">ZIP Code</label>
<div class="controls">
<input type="text" id="zip" placeholder="Required, numeric & 6 chars">
</div>
</div>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" id="email" placeholder="Required">
</div>
</div>
<div class="control-group">
<label class="control-label" for="mfg">Gender</label>
<div class="controls">
<label class="checkbox inline">
<input type="checkbox" id="inlineCheckbox1" value="option1"> Male
</label>
<label class="checkbox inline">
<input type="checkbox" id="inlineCheckbox2" value="option2"> Female
</label>
</div>
</div>
<div class="control-group">
<label class="control-label" for="lang">Language</label>
<div class="controls">
<label class="radio">
<input type="radio" name="optionsRadios" id="optionsRadios1" value="option1" checked>
English
</label>
<label class="radio">
<input type="radio" name="optionsRadios" id="optionsRadios2" value="option2">
Non-English
</label>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="tn tn-success">Submit</button>
</div>
</div>
</form>
</body>
</html>
Теперь мы добавим код JavaScript для отправки данных на сервер в формате XML.
function Endorser() {
// collect data from web form
var userid, password, name, country, zip, email, xmlString, data;
userid = document.getElementById("userid").value;
password = document.getElementById("password").value;
name = document.getElementById("name").value;
country = document.getElementById("country").value;
zip = document.getElementById("zip").value;
email = document.getElementById("email").value;
//creating XMLhttpRequest object
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
//creating the xml string
xmlString ="<userinfo>" +
" <userid>" + escape(userid) + "</userid>" +
" <password>" + escape(password) + "</password>" +
" <name>" + escape(name) + "</name>" +
" <country>" + escape(country) + "</country>" +
" <zip>" + escape(zip) + "</zip>" +
" <email>" + escape(email) + "</email>" +
"</userinfo>";
//alert(data);
// Build the URL to connect to
var url ="save-userinfo.php";
// Open a connection to the server
xhr.open("POST", url, true);
// declaring that the data being sent is in XML format
xhr.setRequestHeader("Content-Type", "text/xml");
// Send the request
xhr.send(xmlString);
}
А теперь мы прикрепим этот код JavaScript к файлу HTML, а также добавим SendToServer () к событию onsubmit формы.
<form class="well-home span6 form-horizontal" name="xml-ajax" id="xml-ajax" onsubmit="SendToServer()">
Обработка данных на сервере
На стороне сервера файл save-userinfo.php будет собирать данные, отправленные по запросу Ajax, а затем эти данные сохраняются в файле XML. Вот код PHP:
<?php
//collect data send as XML
$xml = file_get_contents('php://input');
//open a file handler with read and write permission
$fh = fopen('userinfo.xml', 'r+');
//writing XML string to the new file
fwrite($fh, $xml);
//closing the file handler
fclose($fh);
?>
Поскольку данные отправляются в формате XML, мы собираем данные с помощью file_get_contents('php://input');
, И затем, открыв файл userinfo.xml, мы записали в него содержимое XML.
Получение данных с сервера в формате XML
А теперь мы увидим, как получать данные с сервера в формате XML с помощью Ajax. Мы также увидим, как визуализировать эти данные в браузере. Для этого мы создадим кнопку на стороне клиента. После того, как пользователь нажмет на кнопку, связанный Ajax-скрипт будет извлекать данные из XML-файла на сервере, а затем они будут отображаться в браузере.
Live Demo
Нажмите на кнопку, и последние обновления будут загружены асинхронно из файла недавних обновлений.xml.
XML-код
<rss version="2.0">
<channel>
<title>w3resource.com recent updates</title>
<link>recent-updates.xml</link>
<description>w3resource.com recent updates.</description>
<item>
<title>Ajax Tutorial</title>
<link>/ajax/introduction.php</link>
<description>In this tutorial we will see how to make Ajax work with PHP and MySQL. We will create a small web application. In that, as soon as you start typing an alphabet in the given input field, a request goes to the PHP file via Ajax, a query is made to the MySQL table, it returns some results and then those results are fetched by Ajax and displayed.
</description>
</item>
<item>
<title>Working with Ajax, PHP and MySQL</title>
<link>/ajax/working-with-PHP-and-MySQL.php</link>
<description>This is the first tutorial of the series of Ajax tutorials which covers the introduction to Ajax. The tutorial will help you to get started with Ajax.
</description>
</item>
<item>
<title>JSON Schema Tutorial</title>
<link>/JSON/JSON-Schema.php</link>
<description>In this tutorial we will discuss JSON Schema, a proposed Internet draft defining a JSON media type (application/schema+json). Internet Engineering Task Force defines JSON Schema as follows:</description>
</item>
<item>
<title>Create Responsive Image and Content Slider with Orbit</title>
<link>/zurb-foundation3/orbit.php</link>
<description>Orbit is a JavaScript Image and Content Slider from Zurb Foundation 3, to create image and content slider easily. This tutorial unfolds the nuances of using Orbit.
</description>
</item>
<item>
<title>Create Modal or Popup Windows with Reveal</title>
<link>/zurb-foundation3/reveal.php</link>
<description>You may create Modal or Popup Windows using Reveal - A Jquery Plugin form Zurb Foundaiton 3. In this tutorial, we will see how to use Reveal.
</description>
</item>
<item>
<title>Responsive Web Design with Twitter Bootstrap</title>
<link>/twitter-bootstrap/responsive-design.php</link>
<description>This tutorial is about how to apply responsive design feature into your web layout. And in the course, you will also learn about Responsive Web Design. With the proliferation of mobile devices, it has become almost unavoidable that you don't have a version of your website which users can view well when browsing through mobile devices. And Responsive Web Design is a very efficient way to serve the purpose.
</description>
</item>
<item>
<title>Zurb Foundation 3 Navigation</title>
<link>/zurb-foundation3/navigation.php</link>
<description>In this tutorial you will see how to create Navigations with Zurb Foundation 3. The framework offers navigations for various context and they are capable to be rendered across various devices.
</description>
</item>
<item>
<title>Creating text effects with CSS3 text-shadow</title>
<link>https://w3resource.com/gallery/css3/text-effects-with-css3-text-shadow-property/</link>
<description>With CSS3 text-shadow property, it is much more easier now to create text effects like glowing effect, blurring effect, outlining, flaming effect etc. This document shows how to create text effects with CSS3 text shadow property.
</description>
</item>
<item>
<title>SQL question answer</title>
<link>/sql/question-answer.php</link>
<description>This document is a collection of questions with short and simple answers useful for learning sql as well as for interviews.
</description>
</item>
<item>
<title>HTML5 embed element</title>
<link>/html5/embed-element.php</link>
<description>HTML5 embed element represents external non-HTML application or interactive content. A good example is, when embed element is used to represent a flash movie(SWF file).
</description>
</item>
<item>
<title>PostgreSQL JOIN</title>
<link>https://w3resource.com/PostgreSQL/postgresql-join.php</link>
<description>The main concept which is focusing on a join is that, two or more data sets, when joined, combined there columns into a new set of rows, including each of the columns requested from each of the data sets.
</description>
</item>
<item>
<title>Zurb Foundation 3 Forms</title>
<link>/zurb-foundation3/forms.php</link>
<description>In this tutorial you will see how to create Forms with Zurb Foundation 3. The way Forms can be created with Foundation 3, is versatile. Let's begin with a simple example.
</description>
</item>
<item>
<title>Zurb Foundation 3 Buttons</title>
<link>/zurb-foundation3/buttons.php</link>
<description>In this tutorial you will see how to create Buttons with Zurb Foundation 3. Foundation 3 Buttons are easy to use and customize.
</description>
</item>
<item>
<title>Create multi-device layouts with Zurb Foundation 3 Grid</title>
<link>/zurb-foundation3/grid-to-create-multi-device-layout.php</link>
<description>In this tutorial you will see how to create multi-device layouts with Zurb Foundation 3 Grid. The Grid is 12 column. You may also nest Grids with this Grid system.
</description>
</item>
<item>
<title>Introduction to Zurb Foundation 3</title>
<link>https://w3resource.com/zurb-foundation3/introduction.php</link>
<description>Zurb Foundation 3 is a responsive front-end framework to build web sites and apps fast. It has all the basic as well as advanced features for rapid prototyping. In this document you will get an overview of what this framework may offer.
</description>
</item>
<item>
<title>A Twitter Bootstrap based simple table generator</title>
<link>https://w3resource.com/gallery/javascript/a-twitter-bootstrap-based-simple-table-generator/</link>
<description>This gallery item presents a Twitter Bootstrap based simple table generator. If you are new to front end development, this may help you to understand how to create and manipulate DOM with JavaScript. For others, we hope that it may come handy when you need to create HTML tables quickly for your next project.</description>
</item>
</channel>
</rss>
HTML и JavaScript код
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Retrieve data from server as XML using Ajax</title>
<meta name="description" content="HTML and JavaScript code of example of Retrieve data from server as XML using Ajax by w3resource">
<link href="../includes/bootstrap.css" rel="stylesheet">
<style type="text/css">
body {padding-top: 40px; padding-left: 25%}
li {list-style: none; margin:5px 0 5px 0; color:#FF0000}
</style>
</head>
<body>
<p><button class="btn btn-primary" data-toggle="button" id="w3r_button" onclick="show_updates('recent-updates.xml')">Get recent updates</button></p>
<div id="updates">
</div>
<script type="text/javascript">
function show_updates(url)
{
var xhr;
var output,w3r,w3,i;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xhr=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
output="<div class='well'>";
w3=xhr.responseXML.documentElement.getElementsByTagName("item");
for (i=0;i<w3.length;i++)
{
w3r=w3[i].getElementsByTagName("title");
w3r1=w3[i].getElementsByTagName("link");
{
try
{
output=output + "<p><a href=" + w3r1[0].firstChild.nodeValue + ">" + w3r[0].firstChild.nodeValue + "</a></p>";
}
catch (er)
{
output=output + "<p> </p>";
}
}
w3r=w3[i].getElementsByTagName("description");
{
try
{
output=output + "<p>" + w3r[0].firstChild.nodeValue + "</p><hr>";
}
catch (er)
{
output=output + "<p> </p>";
}
}
}
output=output + "</div>";
document.getElementById('updates').innerHTML=output;
}
}
xhr.open("GET",url,true);
xhr.send();
}
</script>
</body>
</html>
Мы рекомендуем вам поиграть с кодом, высказать свое мнение в разделе комментариев и поделиться этим руководством.
Предыдущая: Работа с Ajax, PHP и MySQL
Далее: Введение в Ajax
Новый контент: Composer: менеджер зависимостей для PHP , R программирования