开发者

Parse External JSON With JQuery $.getJSON?

I want to get a quote from iheartquotes and add it to a div when the page loads. I currently have this code but do not know why it wont work

    <script开发者_如何学Python type="text/javascript">
    $(document).ready(function() {
        $.getJSON('http://iheartquotes.com/api/v1/random?format=json&callback=?', function(data) {
            $(".content").html(json.quote);
        });
    });
    </script>

And the HTML in the body

<div class="content">
This will be replaced with a quote
</div>


The URL returns JSON, not JSON-P, so you can't read it cross domain with JS in a browser.

You could do this server side instead, or find a third party proxy that could convert it to JSON-P (perhaps YQL).


Yes i too agree with @Quentin. This is not possible in client-side as you are trying to access another domain due to Same origin policy.

So you can call a webservice / a static webmethod in an aspx page (using page- methods) from javascript and do this server side and get back the results client-side itself, where you can do this cross-domain.

The following code may help you to do this in server-side,

You could use WebClient for that matter:

     using (var client = new WebClient())
     {
      // Define data to be posted
        var values = new NameValueCollection
        {
            { "key1", "value1" },
            { "key2", "value2" },
        };

        // Send the POST request
         byte[] result = client.UploadValues("http://foo.com", values);

        // This will contain the cookie being set
        string cookie = client.ResponseHeaders[HttpResponseHeader.SetCookie];
    }  

Hope this helps...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜