zoukankan      html  css  js  c++  java
  • js发送get 、post请求

    前言

    我们经常会用到js发送网络请求,这里用到XMLHttpRequest,主要是为了考虑早期的IE。分为三步:创建需要的对象、连接和发送、接收。

    GET请求

    var httpRequest = new XMLHttpRequest();//第一步:建立所需的对象
            httpRequest.open('GET', 'url', true);//第二步:打开连接  将请求参数写在url中  ps:"./Ptest.php?name=test&nameone=testone"
            httpRequest.send();//第三步:发送请求  将请求参数写在URL中
            /**
             * 获取数据后的处理程序
             */
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState == 4 && httpRequest.status == 200) {
                    var json = httpRequest.responseText;//获取到json字符串,还需解析
                    console.log(json);
                }
            };
    

    POST请求

    var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
    httpRequest.open('POST', 'url', true); //第二步:打开连接
    httpRequest.setRequestHeader("Content-type","application/x-www-form-urlencoded");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)
    httpRequest.send('name=teswe&ee=ef');//发送请求 将情头体写在send中
    /**
     * 获取数据后的处理程序
     */
    httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
            var json = httpRequest.responseText;//获取到服务端返回的数据
            console.log(json);
        }
    };
    

    post方式发送json

    var httpRequest = new XMLHttpRequest();//第一步:创建需要的对象
    httpRequest.open('POST', 'url', true); //第二步:打开连接/***发送json格式文件必须设置请求头 ;如下 - */
    httpRequest.setRequestHeader("Content-type","application/json");//设置请求头 注:post方式必须设置请求头(在建立连接后设置请求头)var obj = { name: 'zhansgan', age: 18 };
    httpRequest.send(JSON.stringify(obj));//发送请求 将json写入send中
    /**
     * 获取数据后的处理程序
     */
    httpRequest.onreadystatechange = function () {//请求后的回调接口,可将请求成功后要执行的程序写在其中
        if (httpRequest.readyState == 4 && httpRequest.status == 200) {//验证请求是否发送成功
            var json = httpRequest.responseText;//获取到服务端返回的数据
            console.log(json);
        }
    };
    
  • 相关阅读:
    软件构架实践_阅读笔记04(-11)
    软件构架实践_阅读笔记03(7-9)
    Tsinsen-A1488 : 魔法波【高斯消元+异或方程组】
    Tsinsen-1487:分配游戏【树状数组】
    Tsinsen-1486:树【Trie树 + 点分治】
    Splay初步【bzoj1503】
    Treap初步
    [BZOJ3207] 花神的嘲讽计划Ⅰ
    可持久化Trie树初步
    可持久化线段树初步
  • 原文地址:https://www.cnblogs.com/niuben/p/14676340.html
Copyright © 2011-2022 走看看