同步请求
以下是基本代码。使用时结合实际情况嵌入响应的变量,参数,创建自己的函数等。
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false ); // false 为同步请求
xmlHttp.send( null );
return xmlHttp.responseText;
}
但是,不鼓励同步请求,因此您可以使用异步请求方式:
异步请求
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText); // 这里获得返回数据。如有需要,结合实际情况进行解析处理。
}
xmlHttp.open("GET", theUrl, true); // true 为异步
xmlHttp.send(null);
}
jQuery方法示例
<script>
function httpGetAsync(theUrl)
{
const Url = theUrl;
$.ajax({
url:Url,
type:'GET',
sccess:function(result){
cosole.log(result);
},
error:function(error){
console.log('Error!');
}
});
}
$(window).on("load",function(){
httpGetAsync('https://www.google.com/ping?sitemap=https://10.1pxeye.com/sitemap.xml');
});
</script>
由于请求地址是google,国内服务器会返回Error!。
评论区
发表新的留言
您可以留言提出您的疑问或建议。
您的留言得到回复时,会通过您填写的邮箱提醒您。