开发者

response from server

开发者 https://www.devze.com 2022-12-22 11:07 出处:网络
When I create request to the server: <script language=\"javascript\" type=\"text/javascript\"> function ajaxFunction()

When I create request to the server:

<script language="javascript" type="text/javascript">
function ajaxFunction()
var ajaxRequest;
try{
ajaxRequest = new XMLHttpRequest();
} catch (e){
try{
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
alert("Your browser broke!");
return false;
}
}

} ajaxRequest.onreadystatechange = function(){

if(ajaxRequest.readyState == 4){

document.write(ajaxRequest.responseText);

document.myForm.time.value = ajaxRequest.responseText;
    }
}
ajaxRequest.open("GET", "http://www.bbc.co.uk", true);
ajaxRequest.send(null); 

}

</script>

Why response is nothing? Why response isnt html code of this开发者_StackOverflow中文版 web site?


This should work (I don't have time to test it right now.)

function ajaxFunction() { //Added open {
    var ajaxRequest;
    try{
    ajaxRequest = new XMLHttpRequest();
    } catch (e){
// Removed additional try / catch
        try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e){
        alert("Your browser broke!");
        return false;
        }
    } 
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            document.write(ajaxRequest.responseText);
            document.myForm.time.value = ajaxRequest.responseText;
        }
    }; // Added semi-colon to the end of the anonymous function definition
ajaxRequest.open("GET", "http://www.bbc.co.uk", true);
ajaxRequest.send(null); 
}

A few notes:

  • White space is not required for the most part in Javascript, but proper indentation makes it much easier to spot syntax errors.
  • When you bind an attribute to an anonymous function you need to follow your } with a ;
  • Once you understand how this works, dig into one of the larger libraries ajax functions / modules. (Learning is always a good thing, and ajax is one of those areas that really needs a few dozen man-hours of work to encounter all the differences between browsers.)+

ADDENDUM:

Cross-domain ajax requests are very difficult to do right (i.e. safely, securely, and without throwing errors) -- they are forbidden to javascript directly by the Same-Domain Origin policy.

See this question and this one for more discussion on the subject and ways to get around it with a proxy or with jsonp

+ jQuery's ajax function is 325 lines long (and that's not counting $.ajax.settings or $.extend())


You might consider using a library like jQuery to do AJAX requests - they handle all the cross-browser quirks for you, and do a lot of extra work to boot. Your code could be as simple as

$.get(
  'http://www.bbc.co.uk',
  function(data) {
    // do something with data
  }
);`
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号