如何用原生js发送jsonp请求

JavaScript019

如何用原生js发送jsonp请求,第1张

//    引入进去

<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>

js使用jsonencode转码在向前端传递数据的时候,我们经常要把数据按照一定格式传递,如json格式,php中用json_encode来转换,但是这里通常会出现一个问题,那就是如果要转换的数据中包含中文,那么json_encode会自动将其中文字符转换成unicode编码。在调用json_encode 的时候我们可以先用urlencode()把它转换成unicode编码,经过json_encode后,再用urldecode解码,这样就能原样把数据传输到前台。在进行JS开发过程中,尤其是在开发报表时,报表已集成到Web页面中,通过在页面传递参数至报表中时,会发现有时某些参数值,传递到报表中是显示为问号或乱码等等一系列不能正常显示的情况。这是由于浏览器和报表服务器的编码不同,字符多次进行编码转换时出现错误导致字符的显示出现乱码,尤其是中日韩文和特殊字符更容易出现乱码问题。

以开发报表软件FineReport为例,在给报表服务器发送请求之前,对URL或者只对URL里面的参数名字和参数值,进行cjkEncode的编码,该方式兼容了各种不同的字符集,如ISO8859-1、 UTF-8、 GBK、 ENU_JP,尤其对中日韩文的处理采取了统一的方案。

最好是使用第一种,然后后台用2个属性接收,或者用对象接收都可以。

第二种一般是后台用字符串接收,比如前端传值是data:str='{"uname":"tom","pwd":123}'

那么后端就用str的String类型接收就可以了!

另外推荐一个JSON工具给您。

JSON在线解析:http://www.sojson.com/