开发者

RESTful API returns data when request originates from browser or PHP, but not from JavaScript. Why?

I'm trying to make calls to a (private) RESTful web service via a GET request using $jQuery.get(). But when I do, I receive no response data (although I do get a 200 OK response code!).

When I make the exact same call from PHP (file_get_contents()) or just by pasting the GET URL into my browser window, I receive the (JSON) response just fine.

Using Firebug, I can see absolutely no difference between the request headers I'm sending when I make the request from jQuery, and when I paste the URL into my browser. The only difference is that jQuery adds "Referer" and "Origin" headers - however, I forcibly added these two headers to my direct browser request using Firefox's ModifyHeaders extension, and I still get the data back, so the service can't be filtering based on Referer/Origin.

So essentially I'm wondering what the hell is going on if I can 开发者_如何学Gomake two seemingly identical requests but receive no response when it's through jQuery. Is there some "hidden" header or parameter that I'm not seeing which the server can use to determine that the request was sent via JavaScript?

My code is as simple as $.get("http://example.com/json.php?q=sometext", function(response) { alert(response); });

Thanks.


Any chance you are violating the same origin policy by trying to send cross domain AJAX requests? If, not make sure that the server sets the proper Content-Type header to application/json so that jQuery automatically provides you with a ready to use parsed object in the success callback. Also try passing a relative url to the $.get function:

$.get("/json.php?q=sometext", function(response) { 
    alert(response); 
});


Try this:

$.get("http://example.com/json.php?q=sometext", 
      function(response) { alert(response); },
      "json");

Note last parameter.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜