What am I missing in the XMLHttpRequest?

后端 未结 3 343
梦如初夏
梦如初夏 2021-01-18 05:20

I\'m completely new to the javascript and ajax world but trying to learn.

Right now I\'m testing the XMLHttpRequest and I can\'t make work even the simplest example.

3条回答
  •  抹茶落季
    2021-01-18 06:04

    You are running into the Same Origin Policy.

    Unless your code is actually running on www.google.com (which is unlikely), this is going to error.

    Also, and while this isn't causing you a problem at the moment, it is poor practice and can lead to race conditions, you are using globals all over the place.

    Make the xhr variable local to the function

    var xhr = new XMLHttpRequest();
    

    And refer to it with this inside the onreadstatechange method.

    if (this.readyState == 4 && this.status == 200){
    // etc etc
    

提交回复
热议问题