views:

69

answers:

2

I want to pull down a feed (like twitter) and place in on a page using javascript (jquery). Ultimately, the "service" just needs to hand off JSON. I created a web service that allows me to do that, sort of. I don't know if using a stream reader is all that efficient and I was a little bothered by having to use what amounts to 2 evals on the clientside.

My question is twofold: is there a better method than using a web service and two, is there a problem with my implementation?

.asmx:

[WebMethod]
public string HelloWorld()
{
    WebRequest request = WebRequest.Create("http://twitter.com/statuses/user_timeline/username.json?count=1");
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    StreamReader reader = new StreamReader(response.GetResponseStream());
    string tmp = reader.ReadToEnd();
    response.Close();
    reader.Close();
    return tmp;
}

.aspx

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript"></script>
<script>
    $(document).ready(function() {
        $.ajax({
            url: "WebService1.asmx/twitter",
            type: "POST",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(obj) {
                var t = eval(obj.d)[0].text;
                $('div').html(t);
            }
        })
    });
</script>
+1  A: 

2 part answer to your question. 1st of all use

System.Net.WebClient client = new System.Net.WebClient();
string twitterFeed = client.DownloadString("http://twitter.com/statuses/user_timeline/username.json?count=1") 

This will return the string without all the excess lines of code.

2nd the twitter api is a webservice that returns json. So you don't need to recreate the wheel. Here is a nice article and a jquery-twitter library that will allow you to easily get your timeline, like this.

$.twitter.user_timeline('username', function(resp){  
  $('body').append('  

'+this.user.name+': '+this.text+'  

');  
}); 
awright18
That first part is a lot cleaner. Thanks. That jquery library will be handy but I guess including twitter in the example may be distracting. I am really trying to create a cross domain solution. Twitter was just easy. But maybe I am overthinking this. If a service serves up json is it always going to be true that a client side library is all I need?
LeRoy
server side request is useful where authentication is required and you don't want leave a password in your script.
Paul Creasey
I would think so, except like Paul says, you may not want to store credentials in your javascript.
awright18
Ok, that is really helpful.
LeRoy
A: 

Your server side code isn't really doing anything, Why aren't you just calling the twitter api directly from the client?

Paul Creasey
I was under the impression that I needed a server component in order to make requests cross domain. I have plans for more than just twitter.
LeRoy