Using ajax to access web from local file

前端 未结 1 515
-上瘾入骨i
-上瘾入骨i 2020-12-09 21:10

i\'m a bit new to JQuery and ajax, so i apologize if this is a newbie\'s question.

I\'m trying to use ajax from a local file to access the web (for example, getting

1条回答
  •  無奈伤痛
    2020-12-09 21:18

    The problem is that you're running into the Same Origin Policy, which applies to all "real" ajax calls (calls actually using XMLHttpRequest).

    The reason IE works but Firefox and Chrome don't is simple: IE doesn't apply the SOP when the origin is a local file and the resource you're trying to retrieve is on the web. Chrome and Firefox, on the other hand, apply the Cross-Origin Resource Sharing standard from the W3C and so include the relevant "this is my origin, will you let me talk to you?" headers — and w3schools is saying "No, I won't talk to you." ("null" is the "origin" value for the local machine.) The joy of having a choice of browsers is that they can make different design decisions on things like this.

    The code you found that works isn't doing a real ajax call, it's doing JSON-P, which doesn't use XMLHttpRequest at all and so bypasses the SOP, but only for GET operations (not POST) and only if the other end supports it. (jQuery's get function can do both real ajax calls and JSON-P, the key to what it's doing is the dataType parameter, which in the example you showed is "jsonp".)

    You may find this article useful. It describes using YQL (an HTML scraping service from Yahoo) as a cross-domain proxy, since YQL supports JSON-P.

    0 讨论(0)
提交回复
热议问题