将 XMLHTTPRequest 转换为$ajax

converting XMLHTTPRequest into $ajax

本文关键字:ajax 转换 XMLHTTPRequest      更新时间:2023-09-26

我正在使用以下代码在小工具中获取Google:

<html>
<head>
<title>Browser</title>
</head>
<body onload= "getListCollection()" style="width:900px; height:900px;" >
<div id="listAttributes" style="width:400px; height:400px;" ></div>
<script>
function getListCollection() {
    var url = "https://www.google.co.uk"  
    xmlhttp = new XMLHttpRequest();
    xmlhttp.open('GET',url,true, 'user', 'password');
    xmlhttp.onreadystatechange = function()
    {
        if(xmlhttp.readyState == 4);
        {
            document.getElementById("listAttributes").innerHTML = xmlhttp.responseText
        }
    }
    xmlhttp.send(null);
}
</script>
</body>
</html>

我想知道如何使用$ajax做同样的事情?

我看了不同的例子,但我不知道它们如何适应这种情况。或者,如果您可以发布一些不错的$ajax教程,请。

当我将其更改为此时,它不起作用:

<html>
<head>
<title>Browser</title>
</head>
<body onload= "getListCollection()" style="width:900px; height:900px;" >
<div id="listAttributes" style="width:400px; height:400px;" ></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">
$.ajax({
    url : 'https://www.google.co.uk',
    type : 'GET',
    success : function(data){
        $('#listAttributes').html(data);
    }
});
</script>
</body>
</html>

页面上没有任何内容。

下面是代码的jQuery版本:

$.ajax({
    url : 'https://www.google.co.uk', //cross-domain? this won't work
    username : 'user',
    password : 'password',
    type : 'GET', //default is GET, but i put it here to clarify
    success : function(data){
        $('#listAttributes').html(data);
    }
});

有关更多详细信息和设置,请阅读jQuery.ajax()文档

类似的东西:

$.ajax({
    url : "https://www.google.co.uk",
    type : "get",
    username : "user",
    password : "password",
    success : function(data) {
        document.getElementById("listAttributes").innerHTML = data;
    }
});
但是,您的

代码很可能不起作用,因为您正在尝试访问外部资源(即不是您的域(。

查看 JQuery Ajax 文档以获取更多详细信息。

$.ajax({
   url: url,
   username: 'user',
   password: 'password'
}).done(function (responseText) {
   document.getElementById('listAttributes').innerHTML = responseText;
   //or
   $("#listAttributes").html(responseText);
});

默认情况下,.ajax将使用GET方法并且是异步的,因此我省略了这些设置。 如果您不需要用户名/密码,我会使用 $.get() .

它非常简单,比纯JavaScript版本更短,这里是:

function getListCollection() {
    $.ajax({
        url: "https://www.google.co.uk",
        username: "user",
        password: "password",
        success: function(data){
            $('listAttributes').html(data);
        }
    });
}

仅当站点支持跨域源时,才会接受该请求。在此处查看 jQuery.ajax(( 文档。