相關的實例代碼,網上要么是你抄抄我的,我抄抄你的,要么就是一堆亂七八糟東西,想學習的看以看看我的代碼,簡潔并且把相關內容正確體現出來,肯定一學就會,其他的就不過是添些輔助判斷罷了
無刷新上傳圖片及顯示數據
第一步建立上傳form,注意enctype要設置成multipart/form-data
<form target="abc" action="index.php" method="post" enctype="multipart/form-data">
<p><input id="input" type="file" name="file" ></p>
<p><input name="sub" type="submit" value="submit"></p>
</form>
在頁面中建立隱藏的iframe分幀,并將name屬性設置成為表單的 的target值
<iframe src="" name="abc" style="display:none"></iframe>
在頁面的js設定中,建立一個函數,本例中是用函數創建Img標簽,將標簽的src屬性設置為等于返回值,
function callback(data){
var obj=document.createElement("img");
obj.src=data;
document.body.appendChild(obj);
}
在服務器端的php設定中,接受上傳的文件,并將新文件的名字賦值給變量參數,在php中echo出一個<script>標簽,中間使用客戶端定義的函數名和當前的變量參數組成一個在<script>標簽中調用父框架函數的js語句
<?php
move_uploaded_file($_FILES['file']['tmp_name'],$_FILES['file']['name']);
$file=$_FILES['file']['name'];
echo "<script>parent.callback('".$file."')</script>";
php讀取js數據
|
|
在html中建立時間觸發按鈕,
<button id="button" name="button" onclick="show()">button</button>
在js中建立ajax函數,向服務器端發送數據請求,并當事件觸發時alert彈出返回的responseText值
function show(){
xhr=new XMLHttpRequest;
xhr.onreadystatechange=function(){
if(xhr.readyState==4 && xhr.status==200){
alert(xhr.responseText);
}
}
xhr.open("post","index.php",true);
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
xhr.send();
}
在服務器端準備一個數組,并且用json_encode函數將數組轉成json格式,然后echo出來,用于客戶端的ajax讀取
<?php
$arr=array("name"=>"user1","age"=>30);
$str=json_encode($arr);
echo $str;
ajax跨域取數據
|
|
在本地的html文件中準備好一個按鈕觸發事件,
<button id="button" name="button" onclick="jsonp()">button</button>
事件將在本頁面新建一個<script>標簽,并將其src屬性設置為要跨域取數據的頁面,在url中傳入本頁要顯示數據的函數名
function jsonp(){
var s1=document.createElement("script");
s1.src="http://localhost/test/index.php?cb=show";
document.body.appendChild(s1);
}
要顯示數據的函數為
var div1obj=document.getElementById("div1");
function show(data){
div1obj.innerHTML=data.name;
}
在遠方的服務器端頁面首先接受GET傳值傳過來的函數名
$show=$_GET['cb'];
準備好json數據
$xjson="{'name':'user1'}";
用php服務器echo出一句話,調用函數名,并把準備好的數據傳入
echo $show."(".$xjson.")";