What am I missing in the XMLHttpRequest?

后端 未结 3 452
梦如初夏
梦如初夏 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:21

    In addition to the same origin policy issue, your alert is in an illogical place. When you use XMLHttpRequest, the function assigned to xhr.onreadystatechange will be called whenever readyState changes. readyState should change (in theory) from 0 (initialized) to 1 (sent) to 2 (loading) to 3 (interactive) to 4 (finished).

    What your code does is check the readyState and see if the request is finished (if (xhr.readyState == 4)), and if not, alert the HTTP status code. Since the request hasn't been sent yet (or has just been sent), there shouldn't be an HTTP status yet.

    Ideally, you should move the alert inside the if block, so it lets you know when it finishes.

提交回复
热议问题