設為首頁

收藏本站

導覽首頁 | 新登場    ◇聯盟溫泉 | 民宿 | 人力銀行 | 女性 |

類型:php_article

Prototype + JSON + PHP
Prototype + JSON + PHP
This week I haven been playing with the great EditArea, a webbased sourcecode editor (examples here). To fetch the data from my PHP server I decided JSON would be the way to go, due to it's clean nature. I soon ran into trouble parsing the JSON data my PHP server threw at the client. It took me a while to figure out how to do this nicely with Prototype, but I found out how at this page (search for responseJSON, which is the magic keyword...) On the server side the key is to make PHP send the header "Content-type: application/json", and print the json_decoded data as response. Prototype can fetch this data by doing an Ajax.Request. On the client side you can let Prototype make an Ajax.Request to the server, and get the property 'responseJSON' from the object you received. Below is a working example. To get it running you need to create these two files, test.html and test.php . You also need the file prototype-1.6.0.2.js in the same directory. I suspect it to work on all Prototype versions from 1.6RC upwards.
test.html
<html>
<head>
  <title>Prototype/JSON/PHP test</title>
  <script language="Javascript" type="text/javascript" src="prototype-1.6.0.2
  <script language="Javascript" type="text/javascript">
  function LoadFile(id,target){
  new Ajax.Request("test.php?action=load&id="+id, {
  onSuccess: function(transport) {
  var theObject = transport.responseJSON;
  $(target).innerHTML = theObject.text;
  }, method: "get"
  });
  }
  </script>
</head>
<body>
  <a href="java, not allowed, script:LoadFile(1,'filelist')">File 1</a>
  <a href="java, not allowed, script:LoadFile(2,'filelist')">File 2</a>
  <a href="java, not allowed, script:LoadFile('third','filelist')">File 3</a>
  <div id="filelist"></div>
</body>
</html>
test.php

<?php
# Make sure this is the first output. 
header('Content-type: application/json'); 
 
# The list of files. 
$files[1]='This is the first file'
$files[2]='And this the second one!'
$files['third']='This must be the third then...'
 
# Get ID and create array. 
$id=$_GET['id']; 
$return['id']=$id
$return['text']=$files[$id]; 
 
# Return the JSON string. 
echo json_encode($return);
 
?>



主旨:

內容:




104休閒信箱 2.3.0 © 104mm.com 2001 - 2017. 您尚未登錄
Page generated in 0.00797582 seconds with 3 Queries