PHP是一種創(chuàng)建動態(tài)交互性站點的服務(wù)器端腳本語言,優(yōu)勢:PHP腳本語言應(yīng)用廣泛,開源免費,最重要的是入門簡單,容易掌握。PHP能夠生成動態(tài)頁面內(nèi)容PHP能夠創(chuàng)建、打開、讀取、寫入、刪除以及關(guān)閉服務(wù)器上的文件PHP能夠接收表單數(shù)據(jù)PHP能夠發(fā)送并取回cookiesPHP能夠添加、刪除、修改數(shù)據(jù)庫中的數(shù)據(jù)PHP能夠限制用戶訪問網(wǎng)站中的某些頁面能夠運行于各種平臺,幾乎兼容所有WEB服務(wù)器,支持多種數(shù)據(jù)庫1.我們想要運行PHP,首先要有個web服務(wù)器,一般可以在本地部署一個服務(wù)器用來測試。所以需要下載個XAMPP,我們在百度搜索apache friends,直接打開第一個鏈接,然后毫不猶豫的下載最新版本(PHP7.0.9),下載后執(zhí)行安裝。2.2.現(xiàn)在來配置XAMPP來部署一個本地服務(wù)器,打開只需要啟用Apache服務(wù),下面我就啟動成功了。如果啟用不成功,Port(s)沒有數(shù)據(jù)顯示,就證明你監(jiān)聽的PC端口被占用,你可以在Config的里第一個選項進行監(jiān)聽端口的更改,找到記事本里的Listen 8080命令改后綴,這里我把監(jiān)聽端口改成空閑的8080了。3.下面來打開Dreamweaver建一個服務(wù)器站點。站點配置:本地站點文件夾一定要選擇你裝Xampp路徑的htdocs的目錄里。4.添加服務(wù)器配置:這樣站點就設(shè)置好了,然后在站點文件夾創(chuàng)建server.php,腳本如下?php //設(shè)置頁面內(nèi)容是html編碼格式是utf-8 //header("Content-Type: text/plain;charset=utf-8"); header('Access-Control-Allow-Origin:*'); header('Access-Control-Allow-Methods:POST,GET'); header('Access-Control-Allow-Credentials:true'); header("Content-Type: application/json;charset=utf-8"); //header("Content-Type: text/xml;charset=utf-8"); //header("Content-Type: text/html;charset=utf-8"); //header("Content-Type: application/javascript;charset=utf-8"); //定義一個多維數(shù)組,包含員工的信息,每條員工信息為一個數(shù)組 $staff = array ( array("name" = "喬布斯", "number" = "101", "sex" = "男", "job" = "IOS開發(fā)工程師"), array("name" = "比爾蓋茨", "number" = "102", "sex" = "男", "job" = "微軟開發(fā)工程師"), array("name" = "陳美麗", "number" = "103", "sex" = "女", "job" = "安卓開發(fā)工程師"), array("name" = "黃力", "number" = "104", "sex" = "男", "job" = "Java開發(fā)工程師"), array("name" = "車神", "number" = "105", "sex" = "男", "job" = "游戲開發(fā)工程師"), array("name" = "測試貓", "number" = "106", "sex" = "男", "job" = "web前端開發(fā)工程師") ); //判斷如果是get請求,則進行搜索;如果是POST請求,則進行新建 //$_SERVER是一個超全局變量,在一個腳本的全部作用域中都可用,不用使用global關(guān)鍵字 //$_SERVER["REQUEST_METHOD"]返回訪問頁面使用的請求方法 if ($_SERVER["REQUEST_METHOD"] == "GET") { search(); } elseif ($_SERVER["REQUEST_METHOD"] == "POST"){ create(); } //通過員工編號搜索員工 function search(){ //檢查是否有員工編號的參數(shù) //isset檢測變量是否設(shè)置;empty判斷值為否為空 //超全局變量 $_GET 和 $_POST 用于收集表單數(shù)據(jù) if (!isset($_GET["number"]) empty($_GET["number"])) { echo '{"success":false,"msg":"參數(shù)錯誤"}'; return; } //函數(shù)之外聲明的變量擁有 Global 作用域,只能在函數(shù)以外進行訪問。 //global 關(guān)鍵詞用于訪問函數(shù)內(nèi)的全局變量 global $staff; //獲取number參數(shù) $number = $_GET["number"]; $result = '{"success":false,"msg":"沒有找到員工。"}'; //遍歷$staff多維數(shù)組,查找key值為number的員工是否存在,如果存在,則修改返回結(jié)果 foreach ($staff as $value) { if ($value["number"] == $number) { $result = '{"success":true,"msg":"找到員工:員工編號:' . $value["number"] . ',員工姓名:' . $value["name"] . ',員工性別:' . $value["sex"] . ',員工職位:' . $value["job"] . '"}'; break; } } echo $result; } //創(chuàng)建員工 function create(){ //判斷信息是否填寫完全 if (!isset($_POST["name"]) empty($_POST["name"]) !isset($_POST["number"]) empty($_POST["number"]) !isset($_POST["sex"]) empty($_POST["sex"]) !isset($_POST["job"]) empty($_POST["job"])) { echo '{"success":false,"msg":"參數(shù)錯誤,員工信息填寫不全"}'; return; } //TODO: 獲取POST表單數(shù)據(jù)并保存到數(shù)據(jù)庫 //提示保存成功 echo '{"success":true,"msg":"員工:' . $_POST["name"] . ' 信息保存成功!"}'; } ? 我們可以在server.php文件數(shù)組$staff里的數(shù)據(jù)進行查詢,并且可以實現(xiàn)添加數(shù)據(jù)的功能,下面來創(chuàng)建demo.htmlstyle body,input,button,select,h1{ font-size:20px; line-height:18px; } /style script window.onload=function(){ document.getElementById("search").onclick=function(){//查詢數(shù)據(jù) //發(fā)送Ajax查詢請求并處理 var request=new XMLHttpRequest(); //open("方法(GET查詢,POST添加)","打開的文件數(shù)據(jù)",處理方式(同步為false異步為true,不填默認為true)); request.open("GET","server.php?number="+document.getElementById('keyword').value); request.send(); request.onreadystatechange=function(){ if(request.readyState===4){//當服務(wù)器請求完成 if(request.status===200){//status==200為服務(wù)器請求成功 var data=JSON.parse(request.responseText); if(data.success){//數(shù)據(jù)填寫符合要求 document.getElementById('searchResult').innerHTML=data.msg; }else{//數(shù)據(jù)填寫不符號要求 document.getElementById('searchResult').innerHTML="出現(xiàn)錯誤:"+data.msg; } }else{//服務(wù)器請求失敗 alert("發(fā)生錯誤:"+request.status); } } } } document.getElementById("save").onclick=function(){//添加數(shù)據(jù) //發(fā)送Ajax添加數(shù)據(jù)請求并處理 var request=new XMLHttpRequest(); //open("方法(GET查詢,POST添加)","打開的文件數(shù)據(jù)",處理方式(同步為false異步為true,不填默認為true));; request.open("POST","server.php"); //定義data取得用戶所填寫的數(shù)據(jù),并且send(data)到服務(wù)器 var data="name="+document.getElementById("staffName").value +"number="+document.getElementById("staffNumber").value +"sex="+document.getElementById("staffSex").value +"job="+document.getElementById("staffJob").value; request.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//在POST方法里必寫,否則添加數(shù)據(jù)不起作用 request.send(data); request.onreadystatechange=function(){ if(request.readyState===4){//當服務(wù)器請求完成 if(request.status===200){//status==200為服務(wù)器請求成功 var data=JSON.parse(request.responseText); if(data.success){//數(shù)據(jù)填寫符合要求 document.getElementById('createResult').innerHTML=data.msg; }else{//數(shù)據(jù)填寫不符合要求 document.getElementById('createResult').innerHTML="出現(xiàn)錯誤:"+data.msg; } }else{//服務(wù)器請求失敗 alert("發(fā)生錯誤:"+request.status); } } } } } /script body h1員工查詢/h1 label請輸入員工編號:/label input type="text" id="keyword"/ button id="search"查詢/button p id="searchResult"/p h1員工創(chuàng)建/h1 label請輸入員工姓名:/label input type="text" id="staffName"/br label請輸入員工編號:/label input type="text" id="staffNumber"/br label請輸入員工性別:/label select id="staffSex" option男/option option女/option /selectbr label請輸入員工職位:/label input type="text" id="staffJob"/br button id="save"保存/button p id="createResult"/p /body 以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
創(chuàng)新互聯(lián)公司專注于昌黎網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供昌黎營銷型網(wǎng)站建設(shè),昌黎網(wǎng)站制作、昌黎網(wǎng)頁設(shè)計、昌黎網(wǎng)站官網(wǎng)定制、成都微信小程序服務(wù),打造昌黎網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供昌黎網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。
用 webservice 來從服務(wù)器獲取數(shù)據(jù),其中你可以選擇用 soap或者 rest 風格的來實現(xiàn)這個 接口。最近也寫了個 soap類型的 還可以 就是比較的重;現(xiàn)在在看 rest 我采用的是 tonic框架,有興趣可以去了解下.
使用守則
首先,我們要創(chuàng)建Web服務(wù),從MySQL數(shù)據(jù)庫中讀取數(shù)據(jù)。
?php
pre/* require the user as the parameter */
pre//
if(isset($_GET['user']) intval($_GET['user'])) {
/* soak in the passed variable or set our own */
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
$user_id = intval($_GET['user']); //no default
/* connect to the db */
$link = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE post_author =
// $user_id AND post_status = 'publish' ORDER BY ID DESC LIMIT $number_of_posts";
$query = "SELECT * FROM `test`.`users`;";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
/* create one master array of the records */
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=$post);
}
}
/* output in necessary format */
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=$posts));
}
else {
header('Content-type: text/xml');
echo '';
foreach($posts as $index = $post) {
if(is_array($post)) {
foreach($post as $key = $value) {
echo '',$key,'';
if(is_array($value)) {
foreach($value as $tag = $val) {
echo '',$tag,'',htmlentities($val),'/',$tag,'';
}
}
echo '/',$key,'';
}
}
}
echo '';
}
/* disconnect from the db */
@mysql_close($link);
}
?
下面是代碼為Android活動讀取Web服務(wù)和解析JSON對象:
public void clickbutton(View v) {
try {
//
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
p.setParameter("user", "1");
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "" +
"webservice1.php?user=1format=json";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//
ListNameValuePair nameValuePairs = new ArrayListNameValuePair(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandlerString responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayListHashMapString, String mylist =
new ArrayListHashMapString, String();
for (int i = 0; i jArray.length(); i++) {
HashMapString, String map = new HashMapString, String();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("idusers", jObject.getString("idusers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
這里是PHP代碼,將數(shù)據(jù)發(fā)送到Web服務(wù),并將其保存:
?php
//$json=$_GET ['json'];
$json = file_get_contents('php://input');
$obj = json_decode($json);
//echo $json;
//Save
$con = mysql_connect('localhost','root','123456')
or die('Cannot connect to the DB');
mysql_select_db('TEST',$con);
/* grab the posts from the db */
//$query = "SELECT post_title, guid FROM wp_posts WHERE
// post_author = $user_id AND post_status = 'publish'
// ORDER BY ID DESC LIMIT $number_of_posts";
mysql_query("INSERT INTO `test`.`users` (UserName, FullName)
VALUES ('".$obj-{'UserName'}."', '".$obj-{'FullName'}."')");
mysql_close($con);
//
//$posts = array($json);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=$posts));
?
Android的活動,將數(shù)據(jù)發(fā)送到Web服務(wù)作為一個JSON對象保存在MySQL數(shù)據(jù)庫中
public void clickbuttonRecieve(View v) {
try {
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567"); HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
Toast.makeText(this, result,
Toast.LENGTH_LONG).show();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
知識點
要連接到你的模擬器,你可以使用此鏈接:。
要讀取JSON對象在Web服務(wù)中,您可以使用下面這行代碼:
$json = file_get_contents('php://input');
$obj = json_decode($json);
文章題目:安卓獲取php數(shù)據(jù) 安卓獲取php數(shù)據(jù)的方法
網(wǎng)站URL:http://jinyejixie.com/article6/dosesig.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設(shè)、做網(wǎng)站、網(wǎng)站收錄、外貿(mào)建站、自適應(yīng)網(wǎng)站、網(wǎng)站設(shè)計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)