uyfrjk 发表于 2015-8-30 08:44:28

js与php数据交互,无刷新上传及显示,跨域传参

  相关的实例代码,网上要么是你抄抄我的,我抄抄你的,要么就是一堆乱七八糟东西,想学习的看以看看我的代码,简洁并且把相关内容正确体现出来,肯定一学就会,其他的就不过是添些辅助判断罢了
  无刷新上传图片及显示数据
  第一步建立上传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"></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">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">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.")";
页: [1]
查看完整版本: js与php数据交互,无刷新上传及显示,跨域传参