zoukankan      html  css  js  c++  java
  • ajax的post请求

    get和post是http请求方法最主要的两种方式。

    post:

    来个例子test.html

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Document</title>
    </head>
    <body>
    <input type="password" id="password">
    <input type="button" value="submit" id="submit">
    <div id="txt"></div>
    <script>
    //监听对象
    document.getElementById('submit').onclick = function(){
      var password = document.getElementById('password').value;
      var url = "index.php?password=" + password;
      post(url,function(data){
        document.getElementById('txt').innerHTML = data;
      })
    }
    //简单的post封装
    function post(url,callback,async){
      var xhr = new XMLHttpRequest();
      async = async ? async :true;
      xhr.onreadystatechange = function(){
        if(xhr.readyState == 4){
          callback(xhr.responseText);
        }
      }
      xhr.open("post",param(url)[0],async);
      xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded")
      xhr.send(param(url)[1]);
    }
    function param(url){
      var arr = url.split("?");
      return arr;
    }
    </script>
    </body>
    </html>

    index.php

    <?php
      echo "your password is ".$_POST['password'];
    ?>

    说明一下:post所请求的页面是无法使用缓存,跟get一样的是,post这中请求方式一般也是采用异步。但是还有一个问题没有搞明白,post传递的url中的字符串参数是否需要编码?

  • 相关阅读:
    D. Renting Bikes 二分
    Maximum Absurdity DP + 数学
    模拟 H
    Secrets 数论
    A. Knight Tournament SET的应用
    B. Xenia and Hamming Codeforces 256B GCD,LCM处理字符串
    Alternate Task UVA11728 暴力枚举
    GCD Extreme (II) 欧拉函数的应用
    Bit Magic HDU 4421 2-Sat
    Encoding http://acm.hdu.edu.cn/showproblem.php?pid=1020
  • 原文地址:https://www.cnblogs.com/wang-jiang/p/4512058.html
Copyright © 2011-2022 走看看