求大神原生JS的ajax处理json数据格式的异步请求完整例子,最好能写出面向对象的形式。

JavaScript015

求大神原生JS的ajax处理json数据格式的异步请求完整例子,最好能写出面向对象的形式。,第1张

    //以post方式发送数据为例

    function chuFa() { //html元素事件触发的函数

        var myXMLHttpRequest = null

        if (window.ActiveXObject) {

            myXMLHttpRequest = new ActiveXObject("Microsoft.XMLHTTP")

        } else {

            myXMLHttpRequest = new XMLHttpRequest()

        }

        var url = "xxx.php"

        var data = "key=val" //val一般是从某个html元素中取出的value值

        myXMLHttpRequest.open("post", url, true)

        myXMLHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded")

        myXMLHttpRequest.onreadystatechange = function(){

            if (myXMLHttpRequest.readyState == 4 && myXMLHttpRequest.status == 200) {

                var res = myXMLHttpRequest.responseText

                var jsonObj = eval("("+res+")")

                //接下来就可以使用jsonObj这个json对象取出其中的属性值,做一些修改html元素value值等操作了。

            }        

        }

        myXMLHttpRequest.send(data)

    }

</script

动态加载 那 就是 通过ajax 发出请求 接受 JSON格式的字符串 再转化成 javascript 识别的JSON 对象

也就是 “${themeList}” 就可以了

前台通过URL 到 服务端 请求数据 服务端(返回的必须是JSON格式的) 返回数据 前台处理就行了

//    引入进去

<script>

function ajax(options) {

  options = options || {}

  options.type = (options.type || "GET").toUpperCase()

  options.dataType = options.dataType || 'json'

  options.async = options.async || true

  options.timeout=options.timeout||8000//超时处理,默认8s

  var params = getParams(options.data)

  var timeoutFlag=null

  var xhr

  var that=this

  if (window.XMLHttpRequest) {

      xhr = new XMLHttpRequest()

  } else {

      xhr = new ActiveXObject('Microsoft.XMLHTTP')

  }

  xhr.onreadystatechange = function() {

      if(options.dataType === 'json'){

          if (xhr.readyState == 4) {

              window.clearTimeout(that.timeoutFlag)

              var status = xhr.status

              if (status >= 200 && status < 300) {

                  // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。

                  options.success && options.success(xhr.responseText, xhr.responseXML)

              } else {

                  options.fail && options.fail(status)

              }

          }

      } else {

          if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {

              window.clearTimeout(that.timeoutFlag)

              var oScript = document.createElement('script')

              document.body.appendChild(oScript)

              var callbackname = 'ajaxCallBack'

              oScript.src = options.url + "?" +  params+'&callback='+callbackname

              window['ajaxCallBack'] = function(data) {

                  options.success(data)

                  document.body.removeChild(oScript)

              }

          }

      }

  }

  if (options.type == 'GET') {

      xhr.open("GET", options.url + '?' + params, options.async)

      xhr.send(null)

  } else if (options.type == 'POST') {

      xhr.open('POST', options.url, options.async)

      if(options.contentType=="undefined"||options.contentType==null){

          xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')

          xhr.send(params)

      }else{

          xhr.setRequestHeader('Content-Type', options.contentType)

          xhr.send(JSON.stringify(options.data))

      }

  }

  this.timeoutFlag=window.setTimeout(function(){//计时器,超时后处理

      window.clearTimeout(that.timeoutFlag)

      //options.fail("timeout")

      xhr.abort()

  }.bind(this),options.timeout)

}

function getParams(data) {

  var arr = []

  for (var param in data) {

      arr.push(encodeURIComponent(param) + '=' + encodeURIComponent(data[param]))

  }

  return arr.join('&')

}

</script>

//    使用

<script>

ajax({

    url: "https://xxx.xxx.xxx.xxx/router/rest", //请求地址

    type: 'GET', //请求方式

    async:true,//同步异步设置

    timeout:8000,//超时设置

    data: {

      userName:$("#username").val(),

    phoneNumber:$("#userphone").val(),

    orderType:'8',

    requirementDetail:'',

    method:'homedecapi.decOrder.insertDecOrder',

    orderSource:'无忧居官网PC'

    }, //请求参数

    success: function(response, xml) {

        if(JSON.parse(response).decOrder_insertDecOrder_response){

          // alert("预约成功")

          $("#mypopup").css('display','block')

        }else{

          alert("预约失败")

        }

    },

    fail: function(status) {

        console.log('状态码为' + status) // 此处为请求失败后的回调

    }

})

</script>