开发者

Why this JQuery Ajax call is not working?

开发者 https://www.devze.com 2023-02-11 04:44 出处:网络
<html> <head> <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"></script>
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript" language="javascript">
$.ajax({
    type: "GET",
    cache: false,
    url: 'http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=school',
    contentType: "application/json; charset=utf-8",
    succ开发者_如何学Goess: function(msg) {
    alert(""+msg.length);
  },
  error: function (e) {
            alert("Failed to Get declassification details");
        }});
</script>
</body>
</html>

I am not able to figure out whats going wrong with this AJAX call.WENT Through several SIMILAR question on this forum, but none was working for me.

I have to Get the resultset from Google search in JSON format.


The browser is dropping the request because of cross domain security policy. Try using JSONP (dataType: "jsonp"). Ajax requests to third party websites are normally not possible because of security restrictions. But there are several client-side techniques to work around this restrictions and one of them is JSONP. One thing you will not get from JSONP is notification of network errors or anything that responds nicely to badly formed responses, so you have to accept that as a tradeoff with the ability to invoke services on other domains.

Why and how JSONP works:

  1. Browsers allow you to have a script element get its source from another domain.
  2. The requested page is set up do wrap the JSON response in a function call if the name of the function is supplied in a parameter (usually named 'callback') in the url.
  3. When dataType is 'jsonp', JQuery creates the wrapping function, adds the callback parameter in the url and inserts a script tag in DOM pointing to the URL you requested.
  4. The browser loads the response as a script and executes it, thus calling the JQuery provided function.

See the difference in the response: http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=school

vs

http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=school&callback=jquery_created_function


You should use dataType instead of 'contentType'. Here is code:

$.ajax({
    type: "GET",
    cache: false,
    url: 'http://ajax.googleapis.com/ajax/services/search/local?v=1.0&q=school',
    dataType: "jsonp",
    success: function(msg) {
        alert("" + msg.responseData.results.length);
    },
    error: function(e) {
        alert("Failed to Get declassification details");
    }
});

Here is working example.

From documentation:

contentTypeString When sending data to the server, use this content-type.

dataTypeString The type of data that you're expecting back from the server.

0

精彩评论

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

关注公众号