ajax的get和post的简单使用

ajax的get和post

get:

html+js

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>title</title>
</head>
<body>
    <input type='text' value='jenny' id='username'>
    <input type='button' value='发送ajax请求' id="btnAjax">
<script type="text/javascript">
//获取按钮绑定事件
document.querySelector("#btnAjax").onclick = function(){
    //异步对象
    var ajax = new XMLHttpRequest();
    //获取标签中的值
    var userName = document.querySelector("#username").value;
    console.log(userName)
    //url,method
    ajax.open('get','ajax.php?name='+userName);
    //
    ajax.send();
    ajax.onreadystatechange = function(){
        if(ajax.readyState==4&&ajax.status==200){
            console.log("ajax.responseText============="+ajax.responseText)
        }
    }
}
</script>
</body>
</html>
View Code

后台

<?php
    header("content-type:text/html;charset=utf-8");
    //php中数据拼接用.
    echo $_GET["name"]."你好吗?"
?>
View Code

放在xampp服务器的www文件夹中,通过127.0.0.1打开

输入内容,点击后,成功返回

post

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>title</title>
</head>
<body>
    <input type='text' value='jenny' id='username'>
    <input type='text' value='23' id='age'>
    <input type='button' value='发送ajax请求' id="btnAjax">
<script type="text/javascript">
//获取按钮绑定事件
document.querySelector("#btnAjax").onclick = function(){
    //异步对象
    var ajax = new XMLHttpRequest();
    //获取标签中的值
    var userName = document.querySelector("#username").value;
    var age = document.querySelector("#age").value;
    //url,method,使用post请求
    ajax.open('post','ajax.php');

    //修改发送给服务器的请求报文的内容
    ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded")
    //ajax.send("name=jack&&age=998");
    ajax.send("name="+userName+"&&age="+age);
    ajax.onreadystatechange = function(){
        if(ajax.readyState==4&&ajax.status==200){
            console.log(ajax.responseText)
        }
    }
}
</script>
</body>
</html>
View Code

php

<?php
    header("content-type:text/html;charset=utf-8");
    //php中数据拼接用.
    echo $_POST["name"]."你好吗,你今年".$_POST["age"]
?>
View Code

 

posted @ 2017-10-14 14:05  JennyGao  阅读(137)  评论(0编辑  收藏  举报