Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
景
FormData簡介
The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to multipart/form-data.
大致意思是你可以將數(shù)據(jù)使用FormData對象編譯成鍵值對形式,然后使用XMLHttpRequest技術(shù)向后端發(fā)送數(shù)據(jù)。主要是用來發(fā)送form表單數(shù)據(jù),也可以發(fā)送帶鍵數(shù)據(jù)。這種形式傳輸?shù)臄?shù)據(jù)和一個enctype屬性為multipart/form-data并且采用submit()方法提交的form表單傳輸?shù)臄?shù)據(jù)格式相同。
Ajax使用FormData提交數(shù)據(jù)
只是簡單的示范一下文件上傳,表單數(shù)據(jù)類似,不寫例子了。
Ajax上傳文件-帶form標(biāo)簽的FormData提交
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>測試</title> </head> <body> <form id="upload" method="post"> <input id="file" type="file" name="file"/> <input id="img" type="hidden"/> <input type="submit" value="上傳圖片"> </form> <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> var BASE_URL = '../' $(document).ready(function(){ $('#file').on('change', function() { var formData = new FormData($('#upload')[0]) $.ajax({ url: BASE_URL + 'api/upload', type: 'post', cache: false, data: formData, processData: false, contentType: false, success: function(res) { console.log(res) } }) }) }) </script> </body> </html> <?php print_r($_FILE);exit(); ?>
特點(diǎn):form表單提交,帶有<form>標(biāo)簽,enctype="multipart/form-data"不設(shè)置也可以。
Ajax不帶form標(biāo)簽的FormData提交
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>測試</title> </head> <body> <input id="file" type="file" name="file"/> <input id="img" type="hidden"/> <input type="submit" value="上傳圖片"> <script type="text/javascript" src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> var BASE_URL = '../' $(document).ready(function(){ $('#file').on('change', function() { console.log(this.files) var formData = new FormData() formData.append("file", this.files[0]); $.ajax({ url: BASE_URL + 'api/upload', type: 'post', cache: false, data: formData, processData: false, contentType: false, success: function(res) { console.log(res) } }) }) }) </script> </body> </html> <?php print_r($_FILE);exit(); ?>
沒有<form>標(biāo)簽,基本使用場景中使用的是這種。
Ajax不使用FormData提交數(shù)據(jù)
從參考2來看,上傳文件需要使用使用FileReader對象,并且Ajax不使用FormData提交數(shù)據(jù)略復(fù)雜,幸虧有一些大咖封裝了一下,比如官方提供了一個A little vanilla framework(一點(diǎn)香草??????這個使用原生寫的,不是封裝,,,),再比如ajaxFileUpload(github地址是參考5,官方有示例,試了一下,妥妥的支持IE6..)。
感受
FormData是HTML5新增的屬性,可能在兼容瀏覽器上面會拋棄一些古典(old)瀏覽器,不過簡單;利用純Ajax提交也還好,因為有很多現(xiàn)成的庫,比如jquery,axios...從A little vanilla framework的示例(參考2)來看,基本是根據(jù)form表單的encypt形式,采用相應(yīng)的方式發(fā)送數(shù)據(jù)。
參考
JAX 是一種與服務(wù)器交換數(shù)據(jù)的技術(shù),可以在補(bǔ)充在整個頁面的情況下更新網(wǎng)頁的一部分。接下來通過本文給大家介紹ajax一些常用方法,大家有需要可以一起學(xué)習(xí)。
1.url:
要求為String類型的參數(shù),(默認(rèn)為當(dāng)前頁地址)發(fā)送請求的地址。
2.type:
要求為String類型的參數(shù),請求方式(post或get)默認(rèn)為get。注意其他http請求方法,例如put和delete也可以使用,但僅部分瀏覽器支持。
3.timeout:
要求為Number類型的參數(shù),設(shè)置請求超時時間(毫秒)。此設(shè)置將覆蓋$.ajaxSetup()方法的全局設(shè)置。
4.async:
要求為Boolean類型的參數(shù),默認(rèn)設(shè)置為true,所有請求均為異步請求。如果需要發(fā)送同步請求,請將此選項設(shè)置為false。注意,同步請求將鎖住瀏覽器,用戶其他操作必須等待請求完成才可以執(zhí)行。
5.cache:
要求為Boolean類型的參數(shù),默認(rèn)為true(當(dāng)dataType為script時,默認(rèn)為false),設(shè)置為false將不會從瀏覽器緩存中加載請求信息。
6.data:
要求為Object或String類型的參數(shù),發(fā)送到服務(wù)器的數(shù)據(jù)。如果已經(jīng)不是字符串,將自動轉(zhuǎn)換為字符串格式。get請求中將附加在url后。防止這種自動轉(zhuǎn)換,可以查看 processData選項。對象必須為key/value格式,例如{foo1:"bar1",foo2:"bar2"}轉(zhuǎn)換為&foo1=bar1&foo2=bar2。如果是數(shù)組,JQuery將自動為不同值對應(yīng)同一個名稱。例如{foo:["bar1","bar2"]}轉(zhuǎn)換為&foo=bar1&foo=bar2。
7.dataType:
要求為String類型的參數(shù),預(yù)期服務(wù)器返回的數(shù)據(jù)類型。如果不指定,JQuery將自動根據(jù)http包mime信息返回responseXML或responseText,并作為回調(diào)函數(shù)參數(shù)傳遞。可用的類型如下:
xml:返回XML文檔,可用JQuery處理。
html:返回純文本HTML信息;包含的script標(biāo)簽會在插入DOM時執(zhí)行。
script:返回純文本JavaScript代碼。不會自動緩存結(jié)果。除非設(shè)置了cache參數(shù)。注意在遠(yuǎn)程請求時(不在同一個域下),所有post請求都將轉(zhuǎn)為get請求。
json:返回JSON數(shù)據(jù)。
jsonp:JSONP格式。使用SONP形式調(diào)用函數(shù)時,例如myurl?callback=?,JQuery將自動替換后一個“?”為正確的函數(shù)名,以執(zhí)行回調(diào)函數(shù)。
text:返回純文本字符串。
8.beforeSend:
要求為Function類型的參數(shù),發(fā)送請求前可以修改XMLHttpRequest對象的函數(shù),例如添加自定義HTTP頭。在beforeSend中如果返回false可以取消本次ajax請求。XMLHttpRequest對象是惟一的參數(shù)。
function(XMLHttpRequest){
this; //調(diào)用本次ajax請求時傳遞的options參數(shù)
}
9.complete:
要求為Function類型的參數(shù),請求完成后調(diào)用的回調(diào)函數(shù)(請求成功或失敗時均調(diào)用)。參數(shù):XMLHttpRequest對象和一個描述成功請求類型的字符串。
function(XMLHttpRequest, textStatus){
this; //調(diào)用本次ajax請求時傳遞的options參數(shù)
}
10.success:
要求為Function類型的參數(shù),請求成功后調(diào)用的回調(diào)函數(shù),有兩個參數(shù)。
(1)由服務(wù)器返回,并根據(jù)dataType參數(shù)進(jìn)行處理后的數(shù)據(jù)。
(2)描述狀態(tài)的字符串。
function(data, textStatus){
//data可能是xmlDoc、jsonObj、html、text等等
this; //調(diào)用本次ajax請求時傳遞的options參數(shù)
}
11.error:
要求為Function類型的參數(shù),請求失敗時被調(diào)用的函數(shù)。該函數(shù)有3個參數(shù),即XMLHttpRequest對象、錯誤信息、捕獲的錯誤對象(可選)。ajax事件函數(shù)如下:
function(XMLHttpRequest, textStatus, errorThrown){
//通常情況下textStatus和errorThrown只有其中一個包含信息
this; //調(diào)用本次ajax請求時傳遞的options參數(shù)
}
12.contentType:
要求為String類型的參數(shù),當(dāng)發(fā)送信息至服務(wù)器時,內(nèi)容編碼類型默認(rèn)為"application/x-www-form-urlencoded"。該默認(rèn)值適合大多數(shù)應(yīng)用場合。
13.dataFilter:
要求為Function類型的參數(shù),給Ajax返回的原始數(shù)據(jù)進(jìn)行預(yù)處理的函數(shù)。提供data和type兩個參數(shù)。data是Ajax返回的原始數(shù)據(jù),type是調(diào)用jQuery.ajax時提供的dataType參數(shù)。函數(shù)返回的值將由jQuery進(jìn)一步處理。
function(data, type){
//返回處理后的數(shù)據(jù)
return data;
}
14.dataFilter:
要求為Function類型的參數(shù),給Ajax返回的原始數(shù)據(jù)進(jìn)行預(yù)處理的函數(shù)。提供data和type兩個參數(shù)。data是Ajax返回的原始數(shù)據(jù),type是調(diào)用jQuery.ajax時提供的dataType參數(shù)。函數(shù)返回的值將由jQuery進(jìn)一步處理。
function(data, type){
//返回處理后的數(shù)據(jù)
return data;
}
15.global:
要求為Boolean類型的參數(shù),默認(rèn)為true。表示是否觸發(fā)全局ajax事件。設(shè)置為false將不會觸發(fā)全局ajax事件,ajaxStart或ajaxStop可用于控制各種ajax事件。
16.ifModified:
要求為Boolean類型的參數(shù),默認(rèn)為false。僅在服務(wù)器數(shù)據(jù)改變時獲取新數(shù)據(jù)。服務(wù)器數(shù)據(jù)改變判斷的依據(jù)是Last-Modified頭信息。默認(rèn)值是false,即忽略頭信息。
17.jsonp:
要求為String類型的參數(shù),在一個jsonp請求中重寫回調(diào)函數(shù)的名字。該值用來替代在"callback=?"這種GET或POST請求中URL參數(shù)里的"callback"部分,例如{jsonp:'onJsonPLoad'}會導(dǎo)致將"onJsonPLoad=?"傳給服務(wù)器。
18.username:
要求為String類型的參數(shù),用于響應(yīng)HTTP訪問認(rèn)證請求的用戶名。
19.password:
要求為String類型的參數(shù),用于響應(yīng)HTTP訪問認(rèn)證請求的密碼。
20.processData:
要求為Boolean類型的參數(shù),默認(rèn)為true。默認(rèn)情況下,發(fā)送的數(shù)據(jù)將被轉(zhuǎn)換為對象(從技術(shù)角度來講并非字符串)以配合默認(rèn)內(nèi)容類型"application/x-www-form-urlencoded"。如果要發(fā)送DOM樹信息或者其他不希望轉(zhuǎn)換的信息,請設(shè)置為false。
21.scriptCharset:
要求為String類型的參數(shù),只有當(dāng)請求時dataType為"jsonp"或者"script",并且type是GET時才會用于強(qiáng)制修改字符集(charset)。通常在本地和遠(yuǎn)程的內(nèi)容編碼不同時使用。
案例代碼:
$(function(){
$('#send').click(function(){
$.ajax({
type: "GET",
url: "test.json",
data: {username:$("#username").val(), content:$("#content").val()},
dataType: "json",
success: function(data){
$('#resText').empty(); //清空resText里面的所有內(nèi)容
var html = '';
$.each(data, function(commentIndex, comment){
html += '<div class="comment"><h6>' + comment['username']
+ ':</h6><p class="para"' + comment['content']
+ '</p></div>';
});
、為什么xml
需要服務(wù)器端返回少量的、單一的數(shù)據(jù)
用戶名是否可用 1 / 0
返回兩個數(shù)的和 400
登錄是否成功 true/false
數(shù)據(jù)插是否成功 true/false
如果我們需要從服務(wù)器端返回大量、復(fù)雜的數(shù)據(jù),如何實現(xiàn)?
xml:服務(wù)器端返回xml數(shù)據(jù)
json:服務(wù)器端返回json數(shù)據(jù)
2、格式:
(1)php解析xml
$dom=new DOMDocument();
$dom->loadXML($str);
$nd=$dom->getElementsByTagName("TagName");
$value=$nd->item(0)->nodeValue
$xml=simplexml_load_string($str);
$first = $xml->first;
$second= $xml->second;
(2)js解析xml
var xml=xmlHttp.responseXML;
node=xml.getElementsByTagName("TagName");
node[0].childNodes[0].nodeValue;
3 、案例1:
實現(xiàn)兩個數(shù)的四則運(yùn)算
HTML代碼:
<script language="javascript" src="public.js"></script>
<script>
window.onload=function(){
$('btnOk').onclick=function(){
var f=$('first').value;
var s=$('second').value;
var data='first='+f+'&second='+s;
var xhr=createxhr();
xhr.open('post','demo01.php');
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
//xml --->xml dom對象
var xml=xhr.responseXML;
var str=xml.getElementsByTagName('jia')[0].childNodes[0].nodeValue;
str+='|'+xml.getElementsByTagName('jian')[0].childNodes[0].nodeValue;
str+='|'+xml.getElementsByTagName('cheng')[0].childNodes[0].nodeValue;
str+='|'+xml.getElementsByTagName('chu')[0].childNodes[0].nodeValue;
$('result').innerHTML=str;
}
};
xhr.send(data);
};
};
</script>
<input type="text" id="first" /><br>
<input type="text" id='second' /><br>
<div id='result'></div>
<input type="button" id="btnOk" value="計算" />
理解:
var xml=xhr.responseXML; 得到ajax返回的xmldom對象
xml.getElementsByTagName('jia')[0] :是表示獲取jia這個元素
xml.getElementsByTagName('jia')[0].childNodes:表示獲取jia元素下的所有子節(jié)點(diǎn)
xml.getElementsByTagName('jia')[0].childNodes[0] :表示獲取jia元素下的唯一文本節(jié)點(diǎn)
xml.getElementsByTagName('jia')[0].childNodes[0].nodeValue:文本節(jié)點(diǎn)的值
php代碼:
<?php
$first=$_POST['first'];
$second=$_POST['second'];
$result1=$first+$second;
$result2=$first-$second;
$result3=$first*$second;
$result4=$first/$second;
//要想返回xml,首先連接一個xml格式的字符串
$str='<root>';
$str.='<jia>'.$result1.'</jia>';
$str.='<jian>'.$result2.'</jian>';
$str.='<cheng>'.$result3.'</cheng>';
$str.='<chu>'.$result4.'</chu>';
$str.='</root>';
/*$str=<<<str
<root>
<jia>$result1</jia>
</root>
str;*/
header('Content-type:text/xml');
echo $str;
理解:
得到結(jié)果后,需要使用字符串連接成一個xml格式的字符串,如:需要一個根元素,下面子元素,最后是具體的值,
連接時也可以使用<<<str創(chuàng)建xml字符串
str;
輸出這個字符串時,默認(rèn)的響應(yīng)內(nèi)容類型:text/html,也就是說客戶端仍把代碼當(dāng)做html來進(jìn)行解析,
ajax對象的responeXML是不能得到一個xmldom對象,必須設(shè)置響應(yīng)頭類型為:text/xml,其代碼:header('Content-type:text/xml');
public.js:
function createxhr() {
/*var xhr;
var str = window.navigator.userAgent;
if (str.indexOf('MSIE') > 0) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
} else {
xhr = new XMLHttpRequest();
}
return xhr;*/
try{return new XMLHttpRequest();}catch(e){}
try{return new ActiveXObject('Microsoft.XMLHTTP'); }catch(e){}
alert('請更換瀏覽器!');
}
function $(id){
return document.getElementById(id);
}
4、案例2
在頁面加載之后,將mysql數(shù)據(jù)庫goods表中所有數(shù)據(jù)顯示在表格中
<root>
<goods>
<name>222</name>
<price>55.00</price>
</goods>
<goods>
<name>諾 E661</name>
<price>205.00</price>
</goods>
<goods>
<name>諾 E661</name>
<price>200.00</price>
</goods>
</root>
HTML代碼:
<style>
tr{
background-color:#ffffff;
height:30px;
font-size:12px;
}
</style>
<script language="javascript" src='public.js'></script>
<script>
window.onload=function(){
var xhr=createxhr();
xhr.open('post','demo02.php');
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200)
var xml=xhr.responseXML;
var goods=xml.getElementsByTagName('goods');
for(var i=0;i<goods.length;i++){
//創(chuàng)建行元素
var tr=document.createElement('tr');
//創(chuàng)建序號td元素
var tdID=document.createElement('td');
tdID.innerHTML=i+1;
//創(chuàng)建名稱td元素
var tdName=document.createElement('td');
tdName.innerHTML=goods[i].childNodes[0].childNodes[0].nodeValue;
//創(chuàng)建價格td元素
var tdPrice=document.createElement('td');
tdPrice.innerHTML=goods[i].childNodes[1].childNodes[0].nodeValue;
//將三個td追加到tr元素
tr.appendChild(tdID);
tr.appendChild(tdName);
tr.appendChild(tdPrice);
document.getElementsByTagName('TBODY')[0].appendChild(tr);
}
};
xhr.send(null);
}
</script>
<table id='tbData' width="800" cellspacing="1" cellpadding="4" bgcolor="#336699">
<tr>
<td>序號</td>
<td>商品名稱</td>
<td>商品價格</td>
</tr>
</table>
理解:
創(chuàng)建行元素,
創(chuàng)建單元格元素
將單元格元素追加到行元素中
將行元素追加到表格元素中
php代碼:
<?php
//查詢goods表中所有數(shù)據(jù)并返回
$sql="select name,price from goods order by id desc";
mysql_connect('localhost','root','111111');
mysql_select_db('shop');
mysql_query('set names gb2312');
$result=mysql_query($sql); //發(fā)送sql語句
$num=mysql_num_rows($result); //總行數(shù)
$str='<root>';
for($i=0;$i<$num;$i++){
$row=mysql_fetch_assoc($result);
$str.='<goods>';
$str.='<name>'.iconv('gb2312','utf-8',$row['name']).'</name>';
$str.='<price>'.$row['price'].'</price>';
$str.='</goods>';
}
$str.='</root>';
header('Content-Type:text/xml');
echo $str;
?>
理解:
查詢goods表中所有數(shù)據(jù)
連接xml格式的字符串
表中有多少條數(shù)據(jù)
xml字符串就有幾對goods標(biāo)簽
其中, name字段出現(xiàn)中文,所以需要進(jìn)行轉(zhuǎn)碼 gb2312--utf-8
最后, 輸出xml字符串
*請認(rèn)真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。