Ajax、JSONP常用句式

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)
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容