美文网首页
Ajax、JSONP常用句式

Ajax、JSONP常用句式

作者: 曾祥辉 | 来源:发表于2017-07-18 00:59 被阅读0次

    xhr=new XMLHttpRequest;
    }
    xhr.onreadystatechange=function()
    {
    if (xhr.readyState==4&&xhr.status==200|| xhr.status==304)
    {
    var results = JSON.parse(xhr.responseText);
    var node = document.createElement('div')
    node.innerText = results[i]
    ct.appendChild(node)
    }
    }
    xhr.open("GET","url",true);
    xhr.send();
    }
    //////////////////////////////////////////////////////////////////////////////
    function sendAjax() {
    //构造表单数据
    var formData = new FormData();
    formData.append('username', 'johndoe');
    formData.append('id', 123456);
    //创建xhr对象
    var xhr = new XMLHttpRequest();
    //设置xhr请求的超时时间
    xhr.timeout = 3000;
    //设置响应返回的数据格式
    xhr.responseType = "text";
    //创建一个 post 请求,采用异步
    xhr.open('POST', '/server', true);
    //注册相关事件回调处理函数
    xhr.onload = function(e) {
    if(this.status == 200||this.status == 304){
    alert(this.responseText);
    }
    };
    xhr.ontimeout = function(e) { ... };
    xhr.onerror = function(e) { ... };
    xhr.upload.onprogress = function(e) { ... };

    //发送数据
    xhr.send(formData);
    }
    ////////////////////////////////////////////////////////////////////////////////////
    JSONP模版:

      <script>function getWeather(json) {
      $('.city').text('城市:' + json.result.currentcity)
      $('.date').text('日期:' + json.date)
      $('.weather').text('天气:' + json.result.weather)
    }
    $('#btn').on('click', function () {
      var script = document.createElement('script');
      //script.setAttribute('src', url);
      script.src = 'url?callback=getWeather';
      document.body.appendChild(script);
      document.body.removeChild(script)
    })
    

    相关文章

      网友评论

          本文标题:Ajax、JSONP常用句式

          本文链接:https://www.haomeiwen.com/subject/gajbhxtx.html