简单的ajax数据传输和获取例子

前端之家收集整理的这篇文章主要介绍了简单的ajax数据传输和获取例子前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
<html>
<head>
<Meta http-equiv="Content-Type" content="text/html; charset=utf8" />
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body>
<p>ajax提交信息*************************************************</p>
<form id="ajaxform" name="ajaxform" method="post" action="action.PHP">
    <p>
    email<input type="text" name="email" id="email"/>

    </p>
    <p>
    address<input type="text" name="address" id="address"/>
    </p>
    <p id="msg"></p>
    <p>    
        <input name="Submit" type="button" value="submit" onclick="return checkemail()"/>
    </p>
</form>

<div>
  <p>ajax获取的个人信息*************************************************</p>
  <p id="list"></p>
</div>

<script language="javascript">
function checkemail(){
  var email = $('#email').val();
  var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;

  if($('#email').val() == ""){
    $('#msg').html("please enter the email!");
    $('#email').focus;
    return false;
  }
  else if(!reg.test(email)) {
    $('#msg').html("illegal email!");
    $('#email').focus;
    return false;
  }

  if($('#address').val() == ""){
    $('#msg').html("please enter the address!");
    $('#address').focus;
    return false;
  }
  ajax_post();
}
//ajax提交数据
function ajax_post(){
  $.post("action.PHP",{email:$('#email').val(),address:$('#address').val()},function(data){
    //$('#msg').html("please enter the email!");
    //alert(data);
    $('#msg').html(data);
  },"text");//这里返回的类型有:json,html,xml,text
}

//ajax获取数据
$(function () {  
  $.ajax({  
     url: 'down.PHP',type: 'GET',dataType: 'json',timeout: 1000,cache: false,beforeSend: LoadFunction,//加载执行方法    
     error: erryFunction,//错误执行方法    
     success: succFunction //成功执行方法    
  })  
  function LoadFunction() {  
     $("#list").html('加载中...');  
  }  
  function erryFunction() {  
     alert("error");  
  }  
  function succFunction(tt) {  
     $("#list").html('');
     //eval将字符串转成对象数组  
     //var json = { "id": name": "yangyurong","old": "24" };  
     //json = eval(json);  
     //alert("===name=" + json.uname + ",old=" + json.old);  
     var json = eval(tt); //数组         
     //$.each(json,function (index,item) {  
         //获取数据    
         var name = json.name;  
         var old = json.old;
         $("#list").html(name + " - " + old);  
     //});  
  }  
  }); 
</script>

</body>
</html>


action.PHP

<span style="font-size:14px;"><?PHP
  $email = $_POST["email"];
  $address = $_POST["address"];
  //echo $email;
  //echo $address;
  echo "success<br />";
?></span>


down.PHP
<?PHP
  $arr = array ('name' => '杨蓉蓉','old' => '24');
  echo json_encode($arr);
?>



$.ajax方法详解,点击看文章


demo下载

原文链接:https://www.f2er.com/ajax/162283.html

猜你在找的Ajax相关文章